数组合并中的单键 PHP

Single Key in Array Merge in PHP

我有一个项目数组,其中有一个键 "locations" 将包含另一个项目数组。

有没有办法合并这个键,而不必循环父数组?我正在使用 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
        )

)

显式循环:

$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; },
    []
);