比较和更新PHP数组
我在PHP中有两个数组: 阵列1比较和更新PHP数组,php,arrays,Php,Arrays,我在PHP中有两个数组: 阵列1 Array ( [0] => Array ( [autoid] => t35wmkbg [task] => Zaphod [progress] => incomplete ) [1] => Array ( [autoid] => cwg2yc5q
Array
(
[0] => Array
(
[autoid] => t35wmkbg
[task] => Zaphod
[progress] => incomplete
)
[1] => Array
(
[autoid] => cwg2yc5q
[task] => Arthur
[progress] => incomplete
)
[2] => Array
(
[autoid] => 85q4bcmy
[task] => Ford
[progress] => incomplete
)
[3] => Array
(
[autoid] => yc5qcwg2
[task] => Trillian
[progress] => incomplete
)
)
阵列2
Array
(
[0] => Array
(
[autoid] => t35wmkbg
[task] => Zaphod
[progress] => complete
)
[1] => Array
(
[autoid] => 85q4bcmy
[task] => Ford
[progress] => incomplete
)
[2] => Array
(
[autoid] => cwg2yc5q
[task] => Arthur
[progress] => pending
)
)
我需要:
- 单步执行数组1,并检查数组2中是否存在autoid
- 如果确实存在,请更新
字段以匹配进度
Array
(
[0] => Array
(
[autoid] => t35wmkbg
[task] => Zaphod
[progress] => complete
)
[1] => Array
(
[autoid] => cwg2yc5q
[task] => Arthur
[progress] => pending
)
[2] => Array
(
[autoid] => 85q4bcmy
[task] => Ford
[progress] => incomplete
)
[3] => Array
(
[autoid] => yc5qcwg2
[task] => Trillian
[progress] => incomplete
)
)
如果有人有任何想法或建议,我不确定如何最好地进行此操作。首先更改arr2,使其索引为
autoid
,然后您可以轻松使用它来获取进度值。
然后只需对arr1进行更改,并将更改应用于进度
(如果存在)
$arr1 = [
['autoid' => 't35wmkbg','task' => 'Zaphod','progress' => 'incomplete'],
['autoid' => 'cwg2yc5q', 'task' => 'Arthur', 'progress' => 'incomplete'],
['autoid' => '85q4bcmy', 'task' => 'Ford', 'progress' => 'incomplete'],
['autoid' => 'yc5qcwg2', 'task' => 'Trillian', 'progress' => 'incomplete']
];
$arr2 = [
['autoid' => 't35wmkbg', 'task' => 'Zaphod', 'progress' => 'complete'],
['autoid' => '85q4bcmy', 'task' => 'Ford', 'progress' => 'incomplete'],
['autoid' => 'cwg2yc5q', 'task' => 'Arthur', 'progress' => 'pending']
];
#first make arr2 indexable on the autoid
foreach ($arr2 as $a) {
$arr2search[$a['autoid']] = $a;
}
foreach ($arr1 as $a){
// do we have an autoid in arr2
if ( isset($arr2search[$a['autoid']])){
$a['progress'] = $arr2search[$a['autoid']]['progress'];
}
$merged[] = $a;
}
print_r($merged);
结果
Array
(
[0] => Array
([autoid] => t35wmkbg, [task] => Zaphod, [progress] => complete)
[1] => Array
([autoid] => cwg2yc5q, [task] => Arthur, [progress] => pending )
[2] => Array
([autoid] => 85q4bcmy, [task] => Ford, [progress] => incomplete )
[3] => Array
([autoid] => yc5qcwg2, [task] => Trillian, [progress] => incomplete )
)
这是一个非常简单的任务,涉及一个循环和一些
if
条件。试一试,如果您的代码有特定问题,请将其编辑到问题中。