Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top