Reputation:
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.
Upvotes: 5
Views: 123
Reputation: 78994
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;
}
Upvotes: 0
Reputation: 777
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.
Upvotes: 2