Php 在数组数组上迭代并显示结果
如何访问作为数组的$value[$I]的内容。使用下表中的foreach时运气不佳 其思想是循环遍历$contentArray,并在每次迭代中显示每个子数组中的一项Php 在数组数组上迭代并显示结果,php,arrays,foreach,Php,Arrays,Foreach,如何访问作为数组的$value[$I]的内容。使用下表中的foreach时运气不佳 其思想是循环遍历$contentArray,并在每次迭代中显示每个子数组中的一项 $addsContent = $Adds->selectAdds(10); $sharedArticlesContent = $SharedContent->getSharedContent($topic_selected, $filter_selected); $blogPostsContent = $BlogPost
$addsContent = $Adds->selectAdds(10);
$sharedArticlesContent = $SharedContent->getSharedContent($topic_selected, $filter_selected);
$blogPostsContent = $BlogPosts->getRecentBlogPostsByTopic("business");
$contentArray = array(
$sharedArticlesContent,
$addsContent ,
$blogPostsContent
);
foreach($contentArray as $value)
{
if(count($value)>$maxLength)
{
$maxLength = count($value);
}
}
for($i=0; $i<$maxLength; $i++)
{
foreach($contentArray as $value)
{
if(isset($value[$i]))
{
if($value==$sharedArticlesContent){
$data = $value[$i];
foreach($sharedArticlesContent as $data){
$post_id = $data['id'];
$uploaded_by = $data['uploaded_by'];
$text = $data['text'];
$image = $data['image'];
require 'template1.php';
}
}elseif($value==$addsContent){
//template2
}else{
//template3
}
}
}
}
$addsContent=$Adds->selectAdds(10);
$sharedArticlesContent=$SharedContent->getSharedContent($topic\u selected,$filter\u selected);
$blogPostsContent=$BlogPosts->getRecentBlogPostsByTopic(“业务”);
$contentArray=array(
$sharedArticlesContent,
$addsContent,
$blogPostsContent
);
foreach($contentArray作为$value)
{
如果(计数($value)>maxLength)
{
$maxLength=计数($value);
}
}
对于($i=0;$i您在这里处理的是关联数组,您可以这样访问它:
<?php
$addsContent = $Adds->selectAdds(10);
$sharedArticlesContent = $SharedContent->getSharedContent($topic_selected, $filter_selected);
$blogPostsContent = $BlogPosts->getRecentBlogPostsByTopic("business");
$contentArray = array(
$sharedArticlesContent,
$addsContent ,
$blogPostsContent
);
foreach($contentArray as $value)
{
if(count($value)>$maxLength)
{
$maxLength = count($value);
}
}
for($i=0; $i<$maxLength; $i++)
{
foreach($contentArray as $value)
{
if(isset($value[$i]))
{
if($value==$sharedArticlesContent)
{
$post_id = $value[$i]['id'];
$uploaded_by = $value[$i]['uploaded_by'];
$text = $value[$i]['text'];
$image = $value[$i]['image'];
require 'template1.php';
}
elseif($value==$addsContent)
{
//template2
}
else
{
//template3
}
}
}
}
您不需要foreach
$data
是一个关联数组,您不需要遍历它
if($value==$sharedArticlesContent){
$data = $value[$i];
$post_id = $data['id'];
$uploaded_by = $data['uploaded_by'];
$text = $data['text'];
$image = $data['image'];
require 'template1.php';
}
我之前尝试过,但是我使用了$data=$value[$I];它永远循环,在3个元素之后。这可能与子数组的长度不相等有关吗?不,它不应该永远循环,它将在元素加载后停止。你想加载所有内容吗?尝试过了。它开始很好,然后在相同的$SharedArticleContent项上永远循环……我不太理解你的数据a结构。您能否更新问题以显示$contentArray
和SharedAtriclesContent
?以及您试图从中获得的输出。我不明白“从每个子数组显示一项”是什么意思,因为您有一个从0
到$maxLength
的循环。