在php中结合单维和多维数组

时间:2016-09-18 15:10:51

标签: php arrays multidimensional-array associative-array array-intersect

单维数组

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

多维数组

$arr2 = array(3) {

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

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

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

交叉可以是,

array(2) {

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

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

我曾尝试使用php array_intersect(),   $Data = array_intersect_assoc($arr1,$arr2);  但有些东西不见了。 任何建议和帮助可以表示赞赏。感谢

1 个答案:

答案 0 :(得分:1)

您可以简单地循环并为PID字段分配适当的值。

$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]);
   }
}