我有这个数组,我必须根据他们的id替换值。以下是Original Array
:
[
0 => [
"id" => "70"
"color" => "red"
]
1 => [
"id" => "65"
"color" => "blue"
]
2 => [
"id" => "66"
"color" => "black"
]
3 => [
"id" => "73"
"color" => "red"
]
]
这是我需要插入并替换原始数组中具有相同id
的数组的数组:
0 => [
"id" => "65"
"color" => "white"
]
1 => [
"id" => "66"
"color" => "gold"
]
]
我想要实现的是这样的:
[
0 => [
"id" => "70"
"color" => "red"
]
1 => [
"id" => "65"
"color" => "white"
]
2 => [
"id" => "66"
"color" => "gold"
]
3 => [
"id" => "73"
"color" => "red"
]
]
答案 0 :(得分:1)
试试这段代码:
<?php
$original = [
0 => [
"id" => "70",
"color" => "red" ,
],
1 => [
"id" => "65",
"color" => "blue",
],
2 => [
"id" => "66",
"color" => "black",
],
3 => [
"id" => "73",
"color" => "red",
]
];
$toReplace = [0 => [
"id" => "65",
"color" => "white" ,
],
1 => [
"id" => "66",
"color" => "gold",
]
];
function getColorByKey($key, $toReplace)
{
$result = null;
foreach($toReplace as $k => $value)
{
if($value['id'] == $key)
$result = $value['color'];
}
return $result;
}
foreach($original as $key => $value)
{
$newColor = getColorByKey($value['id'], $toReplace);
$original[$key]['color'] = $newColor !== null ? $newColor : $original[$key]['color'];
}
var_dump($original);
var_dump
的输出:
array(4) {
[0]=>
array(2) {
["id"]=>
string(2) "70"
["color"]=>
string(3) "red"
}
[1]=>
array(2) {
["id"]=>
string(2) "65"
["color"]=>
string(5) "white"
}
[2]=>
array(2) {
["id"]=>
string(2) "66"
["color"]=>
string(4) "gold"
}
[3]=>
array(2) {
["id"]=>
string(2) "73"
["color"]=>
string(3) "red"
}
}
在getColorByKey($key, $toReplace)
循环中使用了一个函数foreach
,其中$key
为id
索引,而$toReplace
是您的第二个数组。
答案 1 :(得分:1)
使用array_column
和array_walk
函数的简单解决方案:
// $arr1 is the original array
// $arr2 is the replacing array
$colours = array_column($arr2, "color", "id");
array_walk($arr1, function(&$v) use($colours){
if (array_key_exists($v["id"],$colours)) {
$v["color"] = $colours[$v["id"]];
}
});
print_r($arr1);
输出:
Array
(
[0] => Array
(
[id] => 70
[color] => red
)
[1] => Array
(
[id] => 65
[color] => white
)
[2] => Array
(
[id] => 66
[color] => gold
)
[3] => Array
(
[id] => 73
[color] => red
)
)
答案 2 :(得分:1)
// $array1 = original array
// $array2 = second array
foreach ($array1 as $key1 => $value)
{
$new[$value['id']] = $key1;
}
foreach ($array2 as $value)
{
if (array_key_exists($value['id'], $new))
{
$key2 = $new[$value['id']];
$array1[$key2]['color'] = $value['color'];
}
else
{
$array1[] = array('id' => $value['id'], 'color' => $value['color']);
// if this color not present, then it adds this to the original array
}
}
echo '<pre>'; print_r($array1);
输出:
Array
(
[0] => Array
(
[id] => 70
[color] => red
)
[1] => Array
(
[id] => 65
[color] => white
)
[2] => Array
(
[id] => 66
[color] => gold
)
[3] => Array
(
[id] => 73
[color] => red
)
)