我有两个数组$ array1和$ array2,数据显示为:
$ ARRAY1:
Array
(
[0] => Array
(
[id] => 222
[issubtask] => true
)
[1] => Array
(
[id] => 444
[issubtask] => false
)
)
$数组2:
Array
(
[0] => Array
(
[id] => 111
[name] => Mark
[isselected] => false
[issubtask] => false
)
[1] => Array
(
[id] => 222
[name] => Tony
[isselected] => false
[issubtask] => false
)
[2] => Array
(
[id] => 333
[name] => Jack
[isselected] => false
[issubtask] => false
)
[3] => Array
(
[id] => 444
[name] => Nick
[isselected] => false
[issubtask] => false
)
)
我想要做的就是从$ array1检查$ array2中匹配的'id',然后用$ array1中'issubtask'的值替换$ array2的'issubtask'值作为'id'。< / p>
我试过了,但$ array2的值没有改变:
foreach ($array1 as $val1) {
foreach ($array2 as $val2) {
// Checking whether IDs match
if ($val2['id'] == $val1['id']) {
$val2['isselected'] = "true";
$val2['issubtask'] = $value1['issubtask'];
}
}
}
print_r($array2);
我期待以下结果,但我得到了之前的$ array2值。
结果$ array2:
Array
(
[0] => Array
(
[id] => 111
[name] => Mark
[isselected] => false
[issubtask] => false
)
[1] => Array
(
[id] => 222
[name] => Tony
[isselected] => true
[issubtask] => true
)
[2] => Array
(
[id] => 333
[name] => Jack
[isselected] => false
[issubtask] => false
)
[3] => Array
(
[id] => 444
[name] => Nick
[isselected] => true
[issubtask] => false
)
)
我不确定我是否采取了正确的方式。任何帮助深表感谢。
谢谢
答案 0 :(得分:2)
您正在更改var的本地值,而不是真正存储在数组中的值。 当你得到这个:
foreach ($array2 as $key2 => $val2) {
// This is wrong : $val2 is a local value only in the foreach
$val2['isselected'] = "true";
// This is ok, you really change the value in the array
$array2[$key2]['isselected'] = true ;
}
以下是您的问题的答案。小心使用true而不是&#34; true&#34;也。
foreach ( $array1 as $field1 )
{
foreach ( $array2 as $key2 => $field2 ) // Note that $field2 is just a local value in this loop
{
if ( $field2['id'] == $field1['id'] ) // Same ID for each field, and field1 has issubtask
{
// You have to change the value contained in $array2[1][222], not the value stored in $field2[issubtask] because this is a local value
$array2[$key2]['issubtask'] = $field1['issubtask'] ; // Here you have to call the "full path" of array2[$key2]
$array2[$key2]['isselected'] = true ;
}
}
}
答案 1 :(得分:1)
直接替换$ array2而不是$ val2。
foreach ($array1 as $val1) {
foreach ($array2 as $k => $v) {
// Checking whether IDs match
if ($v['id'] == $val1['id']) {
$array2[$k]['isselected'] = "true";
$array2[$k]['issubtask'] = $val1['issubtask'];
}
}
}
print_r($array2);