Skip to content
Advertisement

PHP get arrays from one and add to the property of another

I have two arrays. One is taxonomies:

Array
(
    [genres] => Array
        (
            [label] => Genres
            [value] => genres
        )

    [movie_tags] => Array
        (
            [label] => Movie Tags
            [value] => movie_tags
        )

    [portfolio_category] => Array
        (
            [label] => Portfolio Categories
            [value] => portfolio_category
        )

)

and postTypes:

Array
(
    [movies] => Array
        (
            [0] => genres
            [1] => movie_tags
        )

    [portfolio] => Array
        (
            [0] => portfolio_category
        )

)

Is it possible to combine the two arrays to get something like this?

Array
(
    [movies] => Array
        (
            [0] => Array ( [label] => Genres [value] => genres )
            [1] => Array ( [label] => Movie Tags [value] => movie_tags )
        )

    [portfolio] => Array
        (
            [0] => Array ( [label] => Portfolio Categories [value] => portfolio_category )
        )

)

I’m trying to add the label and value from taxonomies array into postTypes array but I’m not sure how to match the keys and combine the arrays. Is this possible with a foreach loop?

Advertisement

Answer

Using array_intersect_key() will prevent any warnings from missing elements in your lookup array.

Code: (Demo)

$result = [];
foreach ($postTypes as $group => $taxKeys) {
    $result[$group] = array_values(
        array_intersect_key(
            $taxonomies,
            array_flip($taxKeys)
        )
    );
}
var_export($result);

Or if there is no risk of missing elements, a classic nesting of loops: (Demo)

$result = [];
foreach ($postTypes as $group => $taxKeys) {
    foreach ($taxKeys as $taxKey) {
        $result[$group][] = $taxonomies[$taxKey];
    }
}
var_export($result);

Or from PHP7.4, you can enjoy arrow functions to use custom functions without needing use: (Demo)

var_export(
    array_map(
        fn($taxKeys) => array_map(
            fn($taxKey) => $taxonomies[$taxKey],
            $taxKeys
        ),
        $postTypes
    )
);

All of the above deliver the same output from the provided sample data.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement