Search code examples
phparraysmultidimensional-arrayarray-merge

Single Key in Array Merge in PHP


I have an array of items, in it is 1 key "locations" that will contain another array of items.

Is there a way to merge this key, without having to loop the parent array? I am working with wordpress and PHP.

Example Array

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
                        )

                )

        )

)

I want to merge only the 'locations' key, so I am left with a seperate array:

Array
(
    [0] => Array
        (
            [term_id] => 334
        )

    [1] => Array
        (
            [term_id] => 335
        )

    [2] => Array
        (
            [term_id] => 336
        )

)

Solution

  • Explicit looping:

    $source_array = [/* Your array here */];
    $new_array = [];
    foreach ($source_array as $item) {
        $new_array[] = ['term_id' => $item['locations'][0]->term_id];
    }
    

    Implicit looping, one of solutions:

    $source_array = [/* Your array here */];
    $new_array = array_reduce(
        $source_array,
        function($t, $v) { $t[] = ['term_id' => $v['locations'][0]->term_id]; return $t; },
        []
    );