in_array 다중값
다음과 같은 여러 값을 확인하려면 어떻게 해야 합니까?
$arg = array('foo','bar');
if(in_array('foo','bar',$arg))
그건 예니까 네가 좀 더 잘 이해할 수 있을 거야, 안 될 거 알아.
목표물과 건초 더미를 교차하고 교차로 수가 목표물의 수와 동일한지 확인합니다.
$haystack = array(...);
$target = array('foo', 'bar');
if(count(array_intersect($haystack, $target)) == count($target)){
// all of $target is in $haystack
}
결과 교점의 크기가 목표값 배열과 동일한지 확인만 하면 다음과 같이 됩니다.$haystack
의 슈퍼셋이다.$target
.
에서 적어도1개의 값이 설정되어 있는지 확인합니다.$target
에도 있다$haystack
, 다음의 체크를 실행할 수 있습니다.
if(count(array_intersect($haystack, $target)) > 0){
// at least one of $target is in $haystack
}
배열을 검색하여 여러 값을 검색하면 다음과 같이 설정된 작업(차이 설정 및 교차 설정)에 해당합니다.
질문에서 원하는 어레이 검색 유형을 지정하지 않았기 때문에 두 가지 옵션을 모두 제공합니다.
모든 바늘이 존재한다.
function in_array_all($needles, $haystack) {
return empty(array_diff($needles, $haystack));
}
$animals = ["bear", "tiger", "zebra"];
echo in_array_all(["bear", "zebra"], $animals); // true, both are animals
echo in_array_all(["bear", "toaster"], $animals); // false, toaster is not an animal
바늘이 하나라도 있다.
function in_array_any($needles, $haystack) {
return !empty(array_intersect($needles, $haystack));
}
$animals = ["bear", "tiger", "zebra"];
echo in_array_any(["toaster", "tiger"], $animals); // true, tiger is an amimal
echo in_array_any(["toaster", "brush"], $animals); // false, no animals here
중요한 고려 사항
찾고 있는 바늘 세트가 작고 사전에 알려진 경우 논리 체인을 사용하는 것만으로 코드가 명확해질 수 있습니다.in_array
예를 들어 다음과 같습니다.
$animals = ZooAPI.getAllAnimals();
$all = in_array("tiger", $animals) && in_array("toaster", $animals) && ...
$any = in_array("bear", $animals) || in_array("zebra", $animals) || ...
if(in_array('foo',$arg) && in_array('bar',$arg)){
//both of them are in $arg
}
if(in_array('foo',$arg) || in_array('bar',$arg)){
//at least one of them are in $arg
}
건초더미에 바늘이 있는지 확인하기 위해 @Rock Kralj answer(최고의 IMO)에서 벗어나면 사용할 수 있습니다.(bool)
대신!!
코드 리뷰 중에 혼란스러울 수 있습니다.
function in_array_any($needles, $haystack) {
return (bool)array_intersect($needles, $haystack);
}
echo in_array_any( array(3,9), array(5,8,3,1,2) ); // true, since 3 is present
echo in_array_any( array(4,9), array(5,8,3,1,2) ); // false, neither 4 nor 9 is present
https://glot.io/snippets/f7dhw4kmju
IMHO 마크 엘리엇의 솔루션은 이 문제에 대한 최선의 해결책입니다.PHP 5.3을 사용하는 어레이 요소 간에 더 복잡한 비교 작업을 수행해야 하는 경우 다음과 같은 사항을 고려할 수도 있습니다.
<?php
// First Array To Compare
$a1 = array('foo','bar','c');
// Target Array
$b1 = array('foo','bar');
// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
if (!in_array($x,$b1)) {
$b=false;
}
};
// Actual Test on array (can be repeated with others, but guard
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);
이것은 폐쇄에 의존합니다. 비교 기능은 훨씬 더 강력해질 수 있습니다.행운을 빕니다.
if(empty(array_intersect([21,22,23,24], $check_with_this)) {
print "Not found even a single element";
} else {
print "Found an element";
}
array_param()는 모든 인수에 존재하는 array1의 모든 값을 포함하는 배열을 반환합니다.키는 보존됩니다.
값이 모든 매개 변수에 있는 array1의 모든 값을 포함하는 배열을 반환합니다.
empty() : 변수가 비어 있는지 여부를 확인합니다.
var가 존재하고 값이 0이 아니면 FALSE를 반환합니다.그렇지 않으면 TRUE가 반환됩니다.
비교 검사를 통해 이 검색을 최적화하려면 저만 수행할 수 있습니다.
public function items_in_array($needles, $haystack)
{
foreach ($needles as $needle) {
if (!in_array($needle, $haystack)) {
return false;
}
}
return true;
}
여러 번 하는 꼴사나운한 일을 하고 싶다면if(in_array(...&&in_array(...
더 빠릅니다.
array_intersect, array_diff 및 in_array를 사용하여 100과 다른 100,000개의 어레이 요소를 사용하여 2에서 15개의 니들을 테스트했습니다.
in_array는 다른 니들에 대해 15x로 해야 할 때도 항상 상당히 빨랐습니다.array_diff도 array_intersect보다 훨씬 빨랐습니다.
따라서 어레이 in_array() 내에 존재하는지 여부를 확인하기 위해 몇 가지 검색만 하는 것이 성능 면에서 가장 좋습니다.실제 차이/일치를 알고 싶다면 array_diff/array_intersect를 사용하는 것이 더 쉬울 것입니다.
아래 보기 흉한 예에서 제가 계산을 잘못했다면 언제든지 말씀해 주십시오.
<?php
$n1 = rand(0,100000);
$n2 = rand(0,100000);
$n2 = rand(0,100000);
$n3 = rand(0,100000);
$n4 = rand(0,100000);
$n5 = rand(0,100000);
$n6 = rand(0,100000);
$n7 = rand(0,100000);
$n8 = rand(0,100000);
$n9 = rand(0,100000);
$n10 = rand(0,100000);
$n11 = rand(0,100000);
$n12 = rand(0,100000);
$n13 = rand(0,100000);
$n14 = rand(0,100000);
$n15 = rand(0,100000);
$narr = [$n1, $n2, $n3, $n4, $n5, $n6, $n7, $n8, $n9, $n10, $n11, $n12, $n13, $n14, $n15];
$arr = [];
for($i = 0; $i<100000 ; $i++)
{
$arr[] = rand(0,100000);
}
function array_in_array($needles, $haystack)
{
foreach($needles as $needle)
{
if (!in_array($needle, $haystack))
{
return false;
}
}
return true;
}
$start_time = microtime(true);
$failed = true;
if(array_in_array($narr, $arr))
{
echo "<br>true0<br>";
}
$total_time = microtime(true) - $start_time;
echo "<hr>";
echo($total_time);
$start_time = microtime(true);
if (
in_array($n1, $arr) !== false &&
in_array($n2, $arr) !== false &&
in_array($n3, $arr) !== false &&
in_array($n4, $arr) !== false &&
in_array($n5, $arr) !== false &&
in_array($n6, $arr) !== false &&
in_array($n7, $arr) !== false &&
in_array($n8, $arr) !== false &&
in_array($n9, $arr) !== false &&
in_array($n10, $arr) !== false &&
in_array($n11, $arr) !== false &&
in_array($n12, $arr) !== false &&
in_array($n13, $arr) !== false &&
in_array($n14, $arr) !== false &&
in_array($n15, $arr)!== false) {
echo "<br>true1<br>";
}
$total_time = microtime(true) - $start_time;
echo "<hr>";
echo($total_time);
$first_time = $total_time;
echo "<hr>";
$start_time = microtime(true);
if (empty($diff = array_diff($narr,$arr)))
{
echo "<br>true2<br>";
}
$total_time = microtime(true) - $start_time;
echo($total_time);
print_r($diff);
echo "<hr>";
echo "<hr>";
if ($first_time > $total_time)
{
echo "First time was slower";
}
if ($first_time < $total_time)
{
echo "First time was faster";
}
echo "<hr>";
$start_time = microtime(true);
if (count(($itrs = array_intersect($narr,$arr))) == count($narr))
{
echo "<br>true3<br>";
print_r($result);
}
$total_time = microtime(true) - $start_time;
echo "<hr>";
echo($total_time);
print_r($itrs);
echo "<hr>";
if ($first_time < $total_time)
{
echo "First time was faster";
}
echo "<hr>";
print_r($narr);
echo "<hr>";
print_r($arr);
언급URL : https://stackoverflow.com/questions/7542694/in-array-multiple-values
'itsource' 카테고리의 다른 글
파일 확장자는 어떻게 확인할 수 있나요? (0) | 2022.11.14 |
---|---|
RegExp를 사용하는 문자열에서 SQL 추출 패턴 (0) | 2022.11.14 |
MySQL에서 사용 가능한 다음 ID 찾기 (0) | 2022.11.14 |
부분 및 템플릿의 복잡한 중첩 (0) | 2022.11.14 |
XAMPP에서 2개의 PHP 버전을 사용하는 방법이 있습니까? (0) | 2022.11.14 |