php - 将包含对象的数组展平/简化为数组数组

标签 php arrays object multidimensional-array flatten

这个“漂亮”的多维数组也是如此:

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 多个数组一定不是最好的主意。我不是在寻找确切的代码,只是在寻找想法。

最佳答案

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

您拥有的解决方案是最好的,因为如果您使用 array_merge(),那么您将不会有冲突的键,并且时间复杂度为 O(n)还不错。

关于php - 将包含对象的数组展平/简化为数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22818245/

相关文章:

php - 分页语法错误

javascript - 如何在javascript中将对象转换为二维数组

c++ - 如何将 3D 数组转换为 1D 数组?

javascript - 使用键的文本字符串访问 JSON 对象的特定部分

javascript - RegExp 适用于 JS 和 PHP,但不适用于 Java

php - Laravel 5.1 - 表格的拆分内容

Java传递变量——向下转型

forms - Grails Command Object与模型重定向以具有相同的url/页面

javascript - 显示多组按钮中的当前按钮

html - 如何使用 Angular 访问 HTML 中的 JSON 数组对象?