检查所有数组值是否存在于另一个数组值中 [英] Check if all array value exist in another array value

查看:101
本文介绍了检查所有数组值是否存在于另一个数组值中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要与另一个数组匹配的数组,第一个数组内的所有值都必须在第二个数组内,因此,如果第二个数组长度小于第一个数组长度,它将自动变为false.例如:

i have an array that i want to match with another array, all the value inside the first array must be inside the second array, so if second array length is less than the first array length it automatically become false. for example:

$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 

推荐答案

您可以使用

array_diff —计算数组的差异

array_diff — Computes the difference of arrays

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

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

<?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";
}

输出:-

  1. https://eval.in/989587

https://eval.in/989588

https://eval.in/989593

https://eval.in/989596

这篇关于检查所有数组值是否存在于另一个数组值中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆