1

I'm having 2 multidimensional arrays on php, and I'm trying to get only the subarrays that have matching column value.

1st Array :

0 => {#1 ▼
    +"name": "John Doe"
    +"education": "Finance"
    +"age": "23"
    +"mark": "10"
  }
1 => {#2 ▼
    +"name": "Jane Doe"
    +"education": "History"
    +"age": "25"
    +"mark": "9"
  }
2 => {#3 ▼
    +"name": "Anne Smith"
    +"education": "Computer Science"
    +"age": "22"
    +"mark": "8"
  }

2nd Array :

0 => {#1 ▼
    +"name": "Bob Builder"
    +"country": "US"
    +"city": "Massachusetts"
  }
1 => {#2 ▼
    +"name": "Jane Doe"
    +"country": "France"
    +"city": "Paris"
  }
2 => {#3 ▼
    +"name": "Anne Smith"
    +"country": "Germany"
    +"city": "Berlin"
  }

I want to match on column name.

Desired output should be as follows :

0 => {#2 ▼
    +"name": "Jane Doe"
    +"country": "France"
    +"city": "Paris"
    +"education": "History"
    +"age": "25"
    +"mark": "9"
  }
1 => {#3 ▼
    +"name": "Anne Smith"
    +"country": "Germany"
    +"city": "Berlin"
    +"education": "Computer Science"
    +"age": "22"
    +"mark": "8"
  }

Any help on this would be appreciated.

1 Answer 1

2

Here is one way to do it.

First, reindex the first array by name. This will simplify matching names in the next part.

$first = array_column($first, null, 'name');

Then iterate the second array. If the person exists in the first array, merge the values from the two arrays and append that to the product. If not, don't do anything, since you're only looking for the intersection.

foreach ($second as $person) {
    if (isset($first[$person['name']])) {
        $product[] = array_merge($first[$person['name']], $person);
    }        
}

One potential problem with this is that names aren't unique, and this will break if you ever have any people with the same name. It would be much better if you had some unique identifier to use for a person rather than name.

Sign up to request clarification or add additional context in comments.

1 Comment

This solution works fine for me, thanks ! I'm taking into consideration that the column I'm going to merge on should be unique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.