如何使用嵌套键从多维中获取列 [英] How to get column from a multidimensional with nested key
问题描述
如何使用嵌套键从多维中获取列
How to get column from a multidimensional with nested key
我有一个多维数组。我必须拉一个键作为列,但它是嵌套的。例如对象访问如何使用最少的代码行或优化代码来实现这一目标。
I have an array which is multidimensional. I have to pull a key as column but it is nested. like object accessing how to achieve this with minimum line of code or optimized.
数组
$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'
],
];
因为这可以通过使用 foreach
完成, array_map()
和 array_column()
becuase this can be done by using foreach
, array_map()
and array_column()
I
使用 array_column()
using array_column()
$result = array_column(array_column($array, 'price'), 'total');
printf($result);
在上面我必须使用 array_column()
两次我不想使用
in above i have to use array_column()
two time that i don't want to use
使用 foreach
using foreach
$result = [];
foreach ($array as $value) {
$result[] = $value['price']['total'];
}
printf($result);
这很好,但是还有更好的方法。
this is working good but is there any better way.
有什么方法可以在 array_column()
中指定嵌套键,例如
is there any way that i can specify nested key in array_column()
like
array_column($array, 'price.total'); // something like this
结果
array: [
0 => 210
1 => 550
2 => 660
]
我已经搜索了,但是找不到这样的问题,我就是这样问的。
i have searched but unable to find any question like this that's way i asked.
预先感谢。
推荐答案
foreach
是更好的方法,即使您可以为自己能想到的性能建立基准。
foreach
is better way to do that even you can do a benchmark for performance you can have idea.
这篇关于如何使用嵌套键从多维中获取列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!