-1

一維陣列相交一維或者多維陣列

$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); 但有些遺失。 任何建議和幫助,可以讚賞。謝謝

+0

我們可以看看'array_intersect()'的嘗試嗎? – halfer

+0

@halfer請參閱編輯的問題。 –

回答

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

完美的作品,謝謝,以及如何掌握數組? –

+0

你只需要堅持像循環基礎知識,並建立你的概念。並熟悉基本的數組功能。 –

+0

why&in'&$ arr' ?.請解釋 –