5

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.

2
  • You can also use array_walk_recursive() if you prefer that syntax. It's the same algorithm in the backend, though. Commented Apr 2, 2014 at 17:41
  • @Sam No, array_walk_recursive() only visits leafnodes Commented Aug 30, 2022 at 22:43

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.