我有一系列项目,其中包含1个关键“位置”,其中包含另一个项目数组。
有没有办法合并这个键,而不必循环父数组?我正在使用wordpress和PHP。
示例数组
Array
(
[0] => Array
(
[title] => Test Property 1
[locations] => Array
(
[0] => WP_Term Object
(
[term_id] => 334
[name] => Los Angeles
[slug] => los-angeles
)
)
)
[1] => Array
(
[title] => Test Property 2
[locations] => Array
(
[0] => WP_Term Object
(
[term_id] => 335
[name] => New York
[slug] => new-york
)
)
)
[2] => Array
(
[title] => Test Property 3
[locations] => Array
(
[0] => WP_Term Object
(
[term_id] => 336
[name] => Baltimore
[slug] => baltimore
)
)
)
)
我想只合并'locations'键,所以我留下了一个单独的数组:
Array
(
[0] => Array
(
[term_id] => 334
)
[1] => Array
(
[term_id] => 335
)
[2] => Array
(
[term_id] => 336
)
)
答案 0 :(得分:1)
显式循环:
$source_array = [/* Your array here */];
$new_array = [];
foreach ($source_array as $item) {
$new_array[] = ['term_id' => $item['locations'][0]->term_id];
}
隐式循环,解决方案之一:
$source_array = [/* Your array here */];
$new_array = array_reduce(
$source_array,
function($t, $v) { $t[] = ['term_id' => $v['locations'][0]->term_id]; return $t; },
[]
);