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

标签 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

有简单的方法吗?

任何帮助都会很好

最佳答案

实际上 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);
?>

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

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

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

关于php 两个数组之间的数组匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35273913/

相关文章:

c++ - 在C++中将制表符分隔的文件读取到数组中

php - 如何编写mysql查询?

php - 如何使用 Twitter 直接消息流作为输入?

php - 为什么 php 时区在本地主机上是正确的,但上传到服务器后不正确?

php - 设计可扩展的点击/分析系统的最佳方式?

arrays - ElasticSearch读取数组上的元素

php - mySQL 多个 WHEN 列时的情况

mysql - 将 Piwik 移至另一个主机,数据库错误 #1044

mysql - Qt MySQL -------- 无法打开包含文件 : 'mysql.h' :

c - 如何在 c 中的未知类型数组中查找最大元素(使用指向函数的指针)