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

流过昼夜 提交于 2019-12-11 10:18:35

问题


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"
}

回答1:


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']
    }
}



回答2:


foreach($multidimensional_array1 as $arr1){
    foreach($multidimensional_array2 as $arr2){
        if($arr2['id']==$arr1['image_id']){
            echo $arr1['imagepath'];
        }
    }
}

Note: The larger the arrays become the longer this will take.



来源:https://stackoverflow.com/questions/13459315/php-compare-2-multidimensional-arrays-and-output-values-if-equal-fields-in-arr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!