Skip to content
Advertisement

Join two associative array based on key using PHP

I have two arrays here:

JavaScript

I want to join them, kind of left join in mysql so the result will be like this

JavaScript

The address will be merged to $array1 based on the id.

Is this possible using PHP? Please help. Thanks.

Advertisement

Answer

You can simplify this problem by using array_column to re-index $array2 by the id values; then it’s simply a question of checking whether data exists for the id value in $array1:

JavaScript

Output:

JavaScript

Demo on 3v4l.org

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