两个数组之间的php数组匹配

时间:2016-02-08 16:00:39

标签: php mysql arrays

$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

有没有简单的方法呢?

任何帮助都会很好

1 个答案:

答案 0 :(得分:1)

实际上array_intersect会做这样的事情。它从这两个数组中创建一个新数组,只保存两个数组中可用的值。

http://php.net/manual/en/function.array-intersect.php

  

array_intersect()返回一个包含所有值的数组   array1存在于所有参数中。请注意,键是   保留。

编辑:你应该使用array-diff,

  

将array1与一个或多个其他数组进行比较并返回   array1中的值,不存在于任何其他数组中。

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);
?>

我使用了上面描述的两个函数以及以下内容:

http://php.net/manual/en/function.array-unique.php

http://php.net/manual/en/function.array-merge.php

相关问题