2

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

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

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

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

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

4

3 回答 3

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

于 2012-11-05T10:56:24.360 回答
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

}
于 2012-11-05T10:55:59.173 回答
0

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

于 2012-11-05T10:56:31.660 回答