PHP中数组合并中的单键
我有一个项目数组,其中有一个关键的“位置”,将包含另一个项目数组 有没有一种方法可以合并此键,而不必循环父数组?我正在使用wordpress和PHP 示例数组PHP中数组合并中的单键,php,arrays,multidimensional-array,array-merge,Php,Arrays,Multidimensional Array,Array Merge,我有一个项目数组,其中有一个关键的“位置”,将包含另一个项目数组 有没有一种方法可以合并此键,而不必循环父数组?我正在使用wordpress和PHP 示例数组 Array ( [0] => Array ( [title] => Test Property 1 [locations] => Array ( [0] => WP_Ter
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
)
)
显式循环:
$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; },
[]
);
你为什么这么害怕循环?这总是通过一个循环来完成的,无论是显式的还是隐式的。。。这是一个wordpress网站。。。已经很重了;)直到你测试-你不能说。哈。是的,但我确实有几年的托管经验,除了wordpress网站之外什么都没有,我知道它“可能”有多重;)