简体   繁体   English

如何在foreach循环内合并数组

[英]How to combine array inside foreach loop

I have this nested array 我有这个嵌套的数组

$lists = [
  [
   {"id": 1, "name": one},
   {"id": 2, "name": two},
   {"id": 3, "name": three},
  ],
  [
   {"id": 4, "name": four},
   {"id": 5, "name": five},
   {"id": 6, "name": six},
  ]
]

What should i do to make this array into one like this. 我应该怎么做才能将此数组变成这样的数组。

[
   {"id": 1, "name": one},
   {"id": 2, "name": two},
   {"id": 3, "name": three},
   {"id": 4, "name": four},
   {"id": 5, "name": five},
   {"id": 6, "name": six},
]

I tried array_merge using this code 我使用此代码尝试了array_merge

$numbers =[];
foreach ($lists as $list) {
    $numbers = array_merge($numbers, $list);
}

But it didn't work. 但这没有用。 It says that argument #2 is not an array. 它说参数#2不是数组。

You can try this way. 您可以尝试这种方式。 I hope it will be helpful 希望对您有所帮助

$lists =array(
 array(
    array("id"=> 1, "name"=> "one"),
    array("id"=> 2, "name"=> "two"),
    array("id"=> 3, "name"=> "three")
  ),
  array(
    array("id"=> 4, "name"=> "four"),
    array("id"=> 5, "name"=> "five"),
    array("id"=> 6, "name"=> "six")

  )
);

    $numbers =array();
foreach ($lists as $list) {

   foreach ($list as $c) {
    array_push($numbers,$c);
   }
}

echo "<pre>";
print_r($numbers);

There are a few issues. 有几个问题。 The initial data is invalid JSON, but this is an aside, I've fixed it in the data below. 初始数据是无效的JSON,但这是一个问题,我已在下面的数据中对其进行了修复。

You are looping over an empty array $lists which you create just before the loop. 您正在遍历在循环之前创建的空数组$lists Here I've created this from the JSON data and removed the array initialisation. 在这里,我是根据JSON数据创建的,并删除了数组初始化。 Lastly you where using $list['numbers'] where numbers isn't defined anywhere ... 最后,您在哪里使用$list['numbers']在哪里没有定义numbers ...

$json = '[
  [
   {"id": 1, "name": "one"},
   {"id": 2, "name": "two"},
   {"id": 3, "name": "three"}
  ],
  [
   {"id": 4, "name": "four"},
   {"id": 5, "name": "five"},
   {"id": 6, "name": "six"}
  ]
]';

$lists = json_decode($json, true);
$numbers =[];
foreach ($lists as $list) {
    $numbers = array_merge($numbers, $list);
}
print_r($numbers);

Update: 更新:

As a guess to what you've added in the comments to the question, try... 作为对问题注释中添加的内容的猜测,请尝试...

$numbers =[];
foreach ($lists['numbers'] as $list) {
    $numbers = array_merge($numbers, $list);
}
print_r($numbers);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM