paschcua paschcua - 1 month ago 8
PHP Question

PHP - Compare 2 multidimensional arrays and output values if equal fields in array

I have 2 Arrays in 2 variables and both of them containing exactly the same values in the fields (in the 1st array = "image_id"-field and in the 2nd array = "ID-field").

I need to compare the 2 fields and would like to output the imagepath string of the 1st array (if the "ID"-field of 1st array and the field of 2nd array are equal)

Something like this:
if "2146" from 1st multi-array is equal to "2146" from 2nd multi-array, then echo apple.jpg..
But how does that work? Its really freakin me out the last days.. thanks in advance for your replies.

$multidimensional_array1:

array(4) {
[0]=>
string(9) "apple.jpg"
["imagepath"]=>
string(9) "apple.jpg"
[1]=>
string(4) "2146"
["image_id"]=>
string(4) "2146"
}

array(4) {
[0]=>
string(10) "ananas.jpg"
["imagepath"]=>
string(10) "ananas.jpg"
[1]=>
string(4) "2037"
["image_id"]=>
string(4) "2037"
}

array(4) {
[0]=>
string(8) "nuts.jpg"
["imagepath"]=>
string(8) "nuts.jpg"
[1]=>
string(4) "2024"
["image_id"]=>
string(4) "2024"
}


$multidimensional_array2:

array(2) {
[0]=>
string(4) "2146"
["ID"]=>
string(4) "2146"
}

array(2) {
[0]=>
string(4) "2037"
["ID"]=>
string(4) "2037"
}

array(2) {
[0]=>
string(4) "2024"
["ID"]=>
string(4) "2024"
}

Answer Source

As long as the arrays have the same keys, length and order, you can iterate over one and and pick values from both.

$len = count($arr1);

for ($i = 0; $i < $len; $i++)
{
    if ($arr1[$i]['image_id'] == $arr2[$i]['ID'])
    {
        // output $arr1[$i]['imagepath']
    }
}

If the information is from two tables in the same database, you would be better off by just joining the tables together. If the arrays are not ordered the same or not of the same length (so that $i might reference different elements in both arrays), use one as a lookup table:

$lookup = array();

foreach ($arr2 as $element)
{
    $lookup[$element['ID']] = $element;
}

foreach ($arr1 as $element)
{
    if (isset($lookup[$element['image_id']]))
    {
        // output $element['imagepath']
    }
}