$all = array ( 0 => 307, 1 => 157, 2 => 234, 3 => 200, 4 => 322, 5 => 324 ); $search_this = array ( 0 => 200, 1 => 234 );
I would like to find out if $all contains all $search_this values and return true or false. Any ideas please?
$all
$search_this
true
false
我觉得你在找互联系统的功能
array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
array_intersect()返回一个数组,其中包含 array1的所有值 在所有参数中都存在。请注意,键是保留的。
array_intersect()
Http://www.php.net/manual/en/function.array-intersect.php
看看 Array _ intersect ()。
$containsSearch = count(array_intersect($search_this, $all)) === count($search_this);
或者说关联数组,看看 Array _ intersect _ assoc ()。
或者对于子数组的递归比较,可以尝试:
<?php namespace App\helpers; class Common { /** * Recursively checks whether $actual parameter includes $expected. * * @param array|mixed $expected Expected value pattern. * @param array|mixed $actual Real value. * @return bool */ public static function intersectsDeep(&$expected, &$actual): bool { if (is_array($expected) && is_array($actual)) { foreach ($expected as $key => $value) { if (!static::intersectsDeep($value, $actual[$key])) { return false; } } return true; } elseif (is_array($expected) || is_array($actual)) { return false; } return (string) $expected == (string) $actual; } }
Array _ diff短一点
$musthave = array('a','b'); $test1 = array('a','b','c'); $test2 = array('a','c'); $containsAllNeeded = 0 == count(array_diff($musthave, $test1)); // this is TRUE $containsAllNeeded = 0 == count(array_diff($musthave, $test2)); // this is FALSE
以前的答案都做了很多不必要的工作。用 Array _ diff。这是最简单的方法:
$containsAllValues = !array_diff($search_this, $all);
这就是你要做的。
这样吧:
function array_keys_exist($searchForKeys = array(), $searchableArray) { $searchableArrayKeys = array_keys($searchableArray); return count(array_intersect($searchForKeys, $searchableArrayKeys)) == count($searchForKeys); }