更优雅的方法来删除中间阵列?

时间:2022-07-19 07:37:02

So is have this "beautiful" multidimensional array:

所以有这个“漂亮的”多维数组:

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

I removed middle arrays to get one with loops (and converted object to array):

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

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

Result is:

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

It gets job done (makes array with 4 arrays in it), but I am wondering what would be more clean way to do this? Yes and looping 1000+ arrays must not be the best idea. I am not looking for exact code, just idea.

它完成了工作(制作了包含4个数组的数组),但我想知道更干净的方法是什么呢?是的,循环1000+阵列绝对不是最好的主意。我不是在寻找确切的代码,只是想法。

2 个解决方案

#1


3  

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

The solution you have is the best because then you won't have conflicting keys if you use array_merge(), and the time complexity is O(n) which is pretty good.

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

#2


1  

Probably not better or faster (not tested) but alternates:

可能不是更好或更快(未测试)但是替代:

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

Or:

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

#1


3  

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

The solution you have is the best because then you won't have conflicting keys if you use array_merge(), and the time complexity is O(n) which is pretty good.

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

#2


1  

Probably not better or faster (not tested) but alternates:

可能不是更好或更快(未测试)但是替代:

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

Or:

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