$a = array('one'=> val, 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten');
$b = array('four'=> val, 'one'=> val, 'eight'=> val, 'five'=> val)
我有两个数组,如上所示。
需要这样的结果:
将输出:
'one' => val
'two' => 0
'three' => 0
'four' => val
'five' => val
'six' => 0
'seven' => 0
'eight' => val
'nine' => 0
'ten' => 0
有简单的方法吗?
任何帮助都会很好
最佳答案
实际上 array_intersect 就是这样做的。它从这两个数组中创建一个新数组,仅保存两个数组中可用的值。
http://php.net/manual/en/function.array-intersect.php
array_intersect()
returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
编辑:你应该使用 array-diff,
Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.
http://php.net/manual/en/function.array-diff.php
上述输出的代码类似于:
<?php
$a = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten');
$b = array('four', 'one', 'eight', 'five');
//Find matches and not matches
$matches = array_intersect($a, $b);
$dontmatches = array_unique(array_merge($a, $b));
//Set all dont matches to 0
for($i = 0; $i<count($dontmatches);$i++)
$dontmatches[$i] = 0;
$final = array_merge($matches, $dontmatches);
print_r($final);
?>
我使用了上面描述的两个函数以及以下函数:
关于php 两个数组之间的数组匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35273913/