我有一个我希望与另一个数组匹配的数组,第一个数组中的所有值必须在第二个数组内,所以如果第二个数组长度小于第一个数组长度,它会自动变为false。例如:
$products = array("soap","milk","book");
$availableProducts = array("soap","tea","oil","milk","book");
$this->matchArray($products,$availableProducts); //return true because all $products value inside $availableProducts value too
$products = array("soap","milk","book");
$availableProducts = array("milk","tea","book","soap","oil");
$this->matchArray($products,$availableProducts); //return true because all $products value inside $availableProducts value too
$products = array("soap","milk","book");
$availableProducts = array("soap","tea","oil","salt","paper");
$this->matchArray($products,$availableProducts); //return false because only one of $products value inside $availableProducts value
$products = array("soap","milk","book");
$availableProducts = array("milk","book");
$this->matchArray($products,$availableProducts); //return false because only two of $products value inside $availableProducts value
答案 0 :(得分:2)
答案 1 :(得分:1)
您可以使用array_diff()
array_diff - 计算数组的差异
将array1与一个或多个其他数组进行比较并返回 array1中的值,不存在于任何其他数组中。
<?php
$products = array("soap","milk","book");
$availableProducts = array("soap","tea","oil","milk","book");
$difference = array_diff($products,$availableProducts);
if(count($difference)==0){
echo "all products availabale";
}else{
echo implode(',',$difference) ." are not available";
}
输出: -