Skip to content
Advertisement

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

I have two arrays. One is taxonomies:

JavaScript

and postTypes:

JavaScript

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

JavaScript

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)

JavaScript

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

JavaScript

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

JavaScript

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