在 php 中组合单维和多维数组
combining single and multidimensional array in php
一维数组
$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);
但有些东西不见了。
任何建议和帮助都将不胜感激。谢谢
您可以简单地遍历并为 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]);
}
}
一维数组
$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);
但有些东西不见了。
任何建议和帮助都将不胜感激。谢谢
您可以简单地遍历并为 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]);
}
}