Search code examples
phparraysobjectmultidimensional-arrayflatten

Flatten/Simplify an array of arrays containing objects to be an array of arrays


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.


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.