-1

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

Boopathi D
  • 361
  • 2
  • 21

1 Answers1

1

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]);
   }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32