我有一个多维数组。我必须提取特定键的值,但它位于数组深处。我正在尝试找到最有效的方法来做到这一点。
$array = [
[
'price' => ['cost' => 200, 'tax' => 10, 'total' => 210],
'otherKey' => 'etc'
],
[
'price' => ['cost' => 500, 'tax' => 50, 'total' => 550],
'otherKey' => 'etc'
],
[
'price' => ['cost' => 600, 'tax' => 60, 'total' => 660],
'otherKey' => 'etc'
],
];
// desired output is contents of "total" keys:
// [210, 550, 660]
我知道这可以通过使用嵌套调用
array_column()
或使用基本的foreach
循环来完成
$result = array_column(array_column($array, 'price'), 'total');
// OR
$result = [];
foreach ($array as $value) {
$result[] = $value['price']['total'];
}
但我希望有某种方法可以在
array_column()
中指定嵌套键,例如
array_column($array, 'price.total');
foreach
是更好的方法,即使你可以做一个你可以知道的性能基准。
另一种选择可能更理想,如果:
就是使用
array_walk_recursive()
。它只会访问“叶子节点”,因此您无需检查元素是否为数组。
以这种方式使用时,输出将是一个扁平数组。
代码:(演示)
$totals = [];
array_walk_recursive(
$array,
function($leafNode, $key) use(&$totals) {
if ($key === 'total') {
$totals[] = $leafNode;
}
}
);
var_export($totals);
否则嵌套
array_column()
调用即可。 演示
var_export(
array_column(
array_column(
$array,
'price'
),
'total'
)
);
或者无体数组解构
foreach()
演示
$result = [];
foreach ($array as ['price' => ['total' => $result[]]]);
var_export($result);
简单的
foreach
应该可以完成这项工作,您还可以编写一个函数,将字符串作为输入,拆分它并从数组中检索值。