搜索数组并返回缺失值

时间:2012-11-05 10:53:48

标签: php arrays

我使用此代码检查数组中是否存在值:

if (!in_array(array("Product code","Price","Supplier","Cost Price"), $data)) {
        die("You are missing fields");
     }

工作正常,但我希望它返回不存在的值,所以如果数组是这样的话:

$data = array("Price","Supplier","Cost Price");

PHP将返回“产品代码不在数组中”

3 个答案:

答案 0 :(得分:4)

使用array_diff查找多个数组比较的差异。

    $array1 = array("a" => "Product code","Price","Supplier","Cost Price");
if (!in_array($array1, $data)) {
        die("You are missing :" . print_r(array_diff($array1, $data)));
     }

从PHP手册:

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);     /* This will print: BLUE */
?>

此处提供更多信息:http://php.net/manual/en/function.array-diff.php

答案 1 :(得分:0)

你可以使用 array_diff_assoc - 使用额外的索引检查来计算数组的差异

<?php
  $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
  $array2 = array("a" => "green", "yellow", "red");
  $result = array_diff_assoc($array1, $array2);
   print_r($result);
?>

或使用in_array之类的

$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}

检查所有数组,你可以使用

之类的东西
foreach($array as $val){
if (in_array($val, $os)) {
        echo "Got Irix";
    }

}else{
     //show error

}

答案 2 :(得分:0)

查看http://www.php.net/manual/en/function.array-diff.phphttp://www.php.net/manual/en/function.array-intersect.php;使用这些函数,您可以检查两个数组的差异(或共同部分),并迭代差异(或公共部分),以告诉用户确切缺少/共同的内容。