构造包含多个数组的数组


Construct array containing many arrays

foreach循环中,我返回一个数组($followerPosts)。

foreach($myfollowers['entities'] as $myfollower)
{
     $followerPosts=$this->displayPostsAction($myfollower->getFollower());
}

我需要在最后有一个包含所有$followerPosts数组的一个大数组。

$bigArray = array();
foreach($myfollowers['entities'] as $myfollower)
{
     $followerPosts=$this->displayPostsAction($myfollower->getFollower());
     $bigArray[] =  $followerPosts;
}

 $bigArray = array();
    foreach($myfollowers['entities'] as $myfollower)
    {
         $bigArray[] =$this->displayPostsAction($myfollower->getFollower());
    }

您可以在循环之前声明一个数组,然后在每次迭代中使用array_merge

或者array_push,这取决于你想做什么

使用array_merge将它们全部放入一个数组中,如下所示:

$big = array();
foreach($myfollowers['entities'] as $myfollower)
{
     $big = array_merge($big, $this->displayPostsAction($myfollower->getFollower()));
}

您必须将它们添加到数组中。

$followerPosts = array()
foreach($myfollowers['entities'] as $myfollower)
{
     //$followerPosts=$this->displayPostsAction($myfollower->getFollower());
     $followerPosts[]=$this->displayPostsAction($myfollower->getFollower());
}
print_r(followerPosts)

就这个目的而言,我认为最好的工具是array_map函数:

$followerPosts = array_map(function($f) {
    return $this->displayPostsAction($f->getFollower());    
}, $myFollowers['entities']);
var_dump($followerPosts);