比较一个数组与另一个数组并替换缺失值php

时间:2014-10-21 23:26:54

标签: php arrays replace compare

我有两个阵列:

$a1=array("Maths","English","Science","ICT");
$a2=array("Maths","ICT");

我想将$ a1与$ a2进行比较,然后返回

$a3=array("Maths",",,",",,","ICT");

所以用“,,”

替换$ a2中的缺失值

这是我的微薄尝试:(

$a1=array("Maths","English","Science","ICT");
$a2=array("Maths","ICT");
$result = array_diff($a1, $a2);
foreach ($result as $v){
$a3 = str_replace($v, ",,", $a1);
}
print_r($a3);

2 个答案:

答案 0 :(得分:1)

很高兴你明白了,但我认为这可能会更好:

<?php

$a1 = array("Maths", "English", "Science", "ICT");
$a2 = array("Maths", "ICT");

$a3 = $a1;

$keys = array_keys(array_diff($a1, $a2));
foreach ($keys as $key)
    $a3[$key] = ',,';

print_r($a3);

Output

Array
(
    [0] => Maths
    [1] => ,,
    [2] => ,,
    [3] => ICT
)

答案 1 :(得分:0)

想出来,谢谢你看:

$a1=array("Maths","English","Science","ICT");
$a2=array("Maths","ICT");

$result = array_diff($a1, $a2);

foreach ($result as $v){

$v = str_replace($result, ",,", $a1);

}
print_r($v);