将包含对象的数组的数组扁平化/简化为一个数组的数组。

5

所以有这样一个“美丽”的多维数组:

array 
  0 => 
    array 
      0 => 
        object(SimpleXMLElement)
          public 'name' => string 'some name'
          public 'model' => string 'some model'
      1 => 
        object(SimpleXMLElement)
          public 'name' => string 'some name'
          public 'model' => string 'some model'
  1 => 
    array 
      0 => 
        object(SimpleXMLElement)
          public 'name' => string 'some name'
          public 'model' => string 'some model'
      1 => 
        object(SimpleXMLElement)
          public 'name' => string 'some name'
          public 'model' => string 'some model'

and so on

我删除了中间数组,得到一个带有循环的数组(并将对象转换为数组):

foreach ($items as $x) {
    foreach ($x as $y) {
        $item[] = (array) $y;
    }
}

结果如下:

array 
  0 => 
    array
      'name' => string 'some name'
      'model' => string 'some model'
  1 => 
    array
      'name' => string 'some name'
      'model' => string 'some model'
  2 => ...
  3 => ...
  etc.

这段代码可以实现目标(创建一个包含4个数组的数组),但我想知道是否有更简洁的方法?循环遍历1000多个数组肯定不是最好的选择。我不需要具体的代码,只需要思路。


如果您更喜欢该语法,也可以使用array_walk_recursive()。但在后端,它是相同的算法。 - Sam Dufel
@Sam 不,array_walk_recursive() 只访问叶节点。 - mickmackusa
2个回答

3
foreach ($items as $x) {
    foreach ($x as $y) {
        $item[] = (array) $y;
    }
}

你所提供的解决方案是最佳的,因为如果你使用 array_merge(),就不会有冲突的键值,同时时间复杂度为O(n),非常优秀。


1

可能不会更好或更快(未经测试),但是可以尝试以下替代方法:

$result = array_map('get_object_vars', call_user_func_array('array_merge', $items));

或者:

foreach(call_user_func_array('array_merge', $items) as $o) {
    $result[] = (array)$o;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接