Search code examples
phpmultidimensional-arrayfilteringassociative-arrayarray-difference

array_diff() based on one column between two arrays with associative rows


I have two multidimensional arrays which are indexed arrays of associative rows.

$array1 = array(
    array('name' => 'foo', 'id' => 12),
    array('name' => 'bar', 'id' => 34),
    array('name' => 'boo', 'id' => 56),
);

$array2 = array(
    array('name' => 'bar', 'id' => 34),
    array('name' => 'boo', 'id' => 56),
    array('name' => 'bar', 'id' => 78),
);

It is possible that rows might have different id values but the same name value -- such as bar in my sample input data.

I need to compare the arrays based on id values only.

Expected Output: (because ids 34 and 56 are found in $array2)

array(
    array('name' => 'foo', 'id' => 12)
)

I tried $one_not_two = array_diff($array1['id'], $array2['id']); which does not return anything.

I also tried $one_not_two = array_diff($array1['id'], $array2['id']);
which returned an error "argument is not an array."

Originally, I got around it by extracting the ids into a one-dimensional array, then just comparing those. Now a new feature in our application requires me to compare the rows while maintaining the multidimensional structure. Any advice?

Our servers are currently running php 5.3 if that makes any difference.


Solution

  • Because the arrays are multidimensional you have to extract the ids like this:

    $ids1 = array();
    foreach($array1 as $elem1)
        $ids1[] = $elem1['id'];
    
    $ids2 = array();
    foreach($array2 as $elem2)
        $ids2[] = $elem2['id'];
    
    $one_not_two = array_diff($ids1,$ids2);
    

    For your specific question, check out array_diff() with multidimensional arrays