userTN userTN - 2 months ago 7
PHP Question

intersecting single and multidimensional array in php

single dimensional array

$arr1 = array(3) {
["Gold"]=> "170"
["Diamond"]=> "301"
["Platinum"]=> "302"
}


multidimensional array

$arr2 = array(3) {

[0]=>
array(2) {
["ID"]=> "p103"
["PID"]=> "301"
}

[1]=>
array(2) {
["ID"]=> "p104"
["PID"]=> "302"
}

[2]=>
array(2) {
["ID"]=> "p105"
["PID"]=> "300"
}
}


And the intersecting can be,

array(2) {

[0]=>
array(2) {
["ID"]=> "301"
["PID"]=> "Diamond"
}

[1]=>
array(2) {
["ID"]=> "302"
["PID"]=> "Platinum"
}
}


I had tried using php
array_intersect()
,
$Data = array_intersect_assoc($arr1,$arr2);

but something was missing.
Any suggestions and help can be appreciated. Thanks

Answer

You could simply loop through and assign appropriate value to the PID field.

`$array1 = array(
   "Gold" => "170",
   "Diamond" => "301",
   "Platinum" => "302"
 );`

 $array2 = array(
   array(
    "ID" => "p103",
    "PID" => "301"
   ),
   array(
    "ID" => "p104",
    "PID" => "302"
  ),
  array(
    "ID" => "p105",
    "PID" => "300"
  )
);

$array1 = array_flip($array1);  // Flipping first array so that we can directly use the values Gold, Diamond corresponding to 301, 301 ...

foreach ($array2 as $k => &$arr) {
   /* 
    * If value exists in array 1 then assign it to PID 
    * Otherwise, unset this array key
    */
   if (isset($array1[$arr['PID']])) {
       $arr['PID'] = $array1[$arr['PID']];  
   } else {
       unset($array2[$k]);
   }
}