这个“漂亮”的多维数组也是如此:
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
我删除了中间数组以获得一个带有循环的数组(并将对象转换为数组):
foreach ($items as $x) {
foreach ($x as $y) {
$item[] = (array) $y;
}
}
结果是:
array
0 =>
array
'name' => string 'some name'
'model' => string 'some model'
1 =>
array
'name' => string 'some name'
'model' => string 'some model'
2 => ...
3 => ...
etc.
它完成了工作(使数组中包含 4 个数组),但我想知道执行此操作的更简洁方法是什么?是的,循环 1000 多个数组一定不是最好的主意。我不是在寻找确切的代码,只是在寻找想法。
最佳答案
foreach ($items as $x) {
foreach ($x as $y) {
$item[] = (array) $y;
}
}
您拥有的解决方案是最好的,因为如果您使用 array_merge()
,那么您将不会有冲突的键,并且时间复杂度为 O(n)
还不错。
关于php - 将包含对象的数组展平/简化为数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22818245/