如何在foreach循环中将数组结果组合在php中

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在foreach循环中将数组结果组合在php中相关的知识,希望对你有一定的参考价值。

请在评论前仔细阅读所有说明,我是新手。

以下是我的php代码

foreach ($mycatarr as $mycat)
{
   $all_posts = all_posts_list($mycat);
}

现在问题是all_posts_list($ mycat)返回数组中的值。我想结合foreach循环生成的所有结果。

*请注意,这里我不想将这些结果存储在另一个数组中。

数组结构

  0 => 
    array (size=9)
      'pid' => string '3' (length=1)
      'userid' => string '6' (length=1)
      'url' => string 'http://buzzlink.local/terms-and-service' (length=39)
      'title' => string 'This is just a test title of the content' (length=40)
      'description' => string 'This is just a normal text description and I am enjoying it while typing in this kind of things as i
' (length=101)
      'credits' => string '20' (length=2)
      'categories' => string '10' (length=2)
      'status' => string '1' (length=1)
      'addtime' => string '1454391098' (length=10)
  1 => 
    array (size=9)
      'pid' => string '16' (length=2)
      'userid' => string '6' (length=1)
      'url' => string 'http://buzzlink.local/terms-and-service' (length=39)
      'title' => string 'This is just a test title of the content' (length=40)
      'description' => string 'This is just a normal text description and I am enjoying it while typing in this kind of things as it helps me to speed up my typing and blah blah blah as this is just a test thing and description.' (length=197)
      'credits' => string '20' (length=2)
      'categories' => string '10' (length=2)
      'status' => string '1' (length=1)
      'addtime' => string '1454391098' (length=10)
答案

使用array_merge:http://us3.php.net/manual/de/function.array-merge.php

foreach ($mycatarr as $mycat)
{
   $all_posts = array_merge($all_posts, all_posts_list($mycat));
}
另一答案

用这个:

$result=[];
foreach ($mycatarr as $mycat){
  $result = array_merge($result, $mycat);
}
print_r($result);

以上是关于如何在foreach循环中将数组结果组合在php中的主要内容,如果未能解决你的问题,请参考以下文章

如何从 foreach 循环中将双精度值附加到 2D 数组,并访问前一个索引?

如何在 foreach 循环中创建数组 - php? [关闭]

php foreach 嵌套循环大数组很慢?

如何使用php在foreach循环中获取多维数组的键? [复制]

在 foreach 循环中绑定数组值时,IMSSP“尝试绑定参数号 0”错误

将数据从 javascript forEach 循环中的 php 数组发送到 ajax 调用的 url