programing

한 배열의 요소가 PHP의 다른 배열에 있는지 확인하는 중

bestcode 2022. 12. 27. 21:19
반응형

한 배열의 요소가 PHP의 다른 배열에 있는지 확인하는 중

PHP에는 다음과 같이 2개의 어레이가 있습니다.

사람:

Array
(
    [0] => 3
    [1] => 20
)

수배자:

Array
(
    [0] => 2
    [1] => 4
    [2] => 8
    [3] => 11
    [4] => 12
    [5] => 13
    [6] => 14
    [7] => 15
    [8] => 16
    [9] => 17
    [10] => 18
    [11] => 19
    [12] => 20
)

People 요소 중 수배 범죄자 배열에 있는 요소가 있는지 확인하려면 어떻게 해야 합니까?

이 예에서는 이 값이 반환됩니다.true왜냐면20수배 중인 범죄자들입니다

를 사용할 수 있습니다.

$result = !empty(array_intersect($people, $criminals));

array_intersect() 및 count()를 사용해도 문제가 없습니다.

예를 들어 다음과 같습니다.

$bFound = (count(array_intersect($criminals, $people))) ? true : false;

'empty'가 최선의 선택이 아닌 경우 다음과 같이 하십시오.

if (array_intersect($people, $criminals)) {...} //when found

또는

if (!array_intersect($people, $criminals)) {...} //when not found

이 코드는 언어 구성에만 변수를 전달할 수 있으므로 유효하지 않습니다. empty()는 언어 구성입니다.

이 작업은 다음 두 줄로 진행해야 합니다.

$result = array_intersect($people, $criminals);
$result = !empty($result);

in_array vs array_intersect 성능 테스트:

$a1 = array(2,4,8,11,12,13,14,15,16,17,18,19,20);

$a2 = array(3,20);

$intersect_times = array();
$in_array_times = array();
for($j = 0; $j < 10; $j++)
{
    /***** TEST ONE array_intersect *******/
    $t = microtime(true);
    for($i = 0; $i < 100000; $i++)
    {
        $x = array_intersect($a1,$a2);
        $x = empty($x);
    }
    $intersect_times[] = microtime(true) - $t;


    /***** TEST TWO in_array *******/
    $t2 = microtime(true);
    for($i = 0; $i < 100000; $i++)
    {
        $x = false;
        foreach($a2 as $v){
            if(in_array($v,$a1))
            {
                $x = true;
                break;
            }
        }
    }
    $in_array_times[] = microtime(true) - $t2;
}

echo '<hr><br>'.implode('<br>',$intersect_times).'<br>array_intersect avg: '.(array_sum($intersect_times) / count($intersect_times));
echo '<hr><br>'.implode('<br>',$in_array_times).'<br>in_array avg: '.(array_sum($in_array_times) / count($in_array_times));
exit;

결과는 다음과 같습니다.

0.26520013809204
0.15600109100342
0.15599989891052
0.15599989891052
0.1560001373291
0.1560001373291
0.15599989891052
0.15599989891052
0.15599989891052
0.1560001373291
array_intersect avg: 0.16692011356354

0.015599966049194
0.031199932098389
0.031200170516968
0.031199932098389
0.031200885772705
0.031199932098389
0.031200170516968
0.031201124191284
0.031199932098389
0.031199932098389
in_array avg: 0.029640197753906

in_array가 최소 5배 빠릅니다.결과가 발견되면 바로 중단됩니다.

다음과 같이 in_array를 사용할 수도 있습니다.

<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
foreach($people as $num) {
    if (in_array($num,$criminals)) {
        $found[$num] = true;
    } 
}
var_dump($found);
// array(2) { [20]=> bool(true)   [2]=> bool(true) }

array_intersect가 사용하기 편리하기는 하지만 성능 면에서는 그다지 우수하지 않은 것으로 나타났습니다.이 스크립트도 작성했습니다.

<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
$fastfind = array_intersect($people,$criminals);
var_dump($fastfind);
// array(2) { [1]=> int(20)   [2]=> int(2) }

그리고 http://3v4l.org/WGhO7/perf#tabs과 http://3v4l.org/g1Hnu/perf#tabs에서 각각 스니펫을 실행하여 성능을 확인했습니다.흥미로운 점은 총 CPU 시간, 즉 사용자 시간 + 시스템 시간이 PHP5.6과 동일하고 메모리도 동일하다는 것입니다.PHP5.4의 총 CPU 시간은 in_array의 경우 array_intersect보다 짧습니다.다만, 약간 짧습니다.

잠시 조사를 한 후에 하는 방법이 있습니다.필드가 "사용 중"인지 확인하는 Laravel API 엔드포인트를 만들고 싶었기 때문에 중요한 정보는 1) 어느 DB 테이블입니까?2) 어떤 DB열? 3) 검색어와 일치하는 값이 해당 열에 있습니까?

이것을 알고 있으면, 어소시에이트 어레이를 구축할 수 있습니다.

$SEARCHABLE_TABLE_COLUMNS = [
    'users' => [ 'email' ],
];

그런 다음 확인할 값을 설정할 수 있습니다.

$table = 'users';
$column = 'email';
$value = 'alice@bob.com';

그럼, 우리가 쓸 수 있다.array_key_exists()그리고.in_array()1단계, 2단계 콤보를 실행한 후 동작합니다.truthy상태:

// step 1: check if 'users' exists as a key in `$SEARCHABLE_TABLE_COLUMNS`
if (array_key_exists($table, $SEARCHABLE_TABLE_COLUMNS)) {

    // step 2: check if 'email' is in the array: $SEARCHABLE_TABLE_COLUMNS[$table]
    if (in_array($column, $SEARCHABLE_TABLE_COLUMNS[$table])) {

        // if table and column are allowed, return Boolean if value already exists
        // this will either return the first matching record or null
        $exists = DB::table($table)->where($column, '=', $value)->first();

        if ($exists) return response()->json([ 'in_use' => true ], 200);
        return response()->json([ 'in_use' => false ], 200);
    }

    // if $column isn't in $SEARCHABLE_TABLE_COLUMNS[$table],
    // then we need to tell the user we can't proceed with their request
    return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}

// if $table isn't a key in $SEARCHABLE_TABLE_COLUMNS,
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);

Larabel 고유의 PHP 코드는 죄송하지만 의사 코드로 읽으실 수 있을 것 같기 때문에 남겨둡니다.중요한 것은 두 가지다.if동기적으로 실행되는 스테이트먼트.

array_key_exists()그리고.in_array()PHP 함수입니다.

출처:

수 입니다.GET /in-use/{table}/{column}/{value}서 (어디서)table,column , , , , 입니다.value★★★★★★★★★★★★★★★★★★」

다음과 같은 경우가 있습니다.

$SEARCHABLE_TABLE_COLUMNS = [
    'accounts' => [ 'account_name', 'phone', 'business_email' ],
    'users' => [ 'email' ],
];

그런 다음 다음과 같은 GET 요청을 할 수 있습니다.

GET /in-use/accounts/account_name/Bob's Drywall 수 보통은 부호화할 필요가 없습니다.

GET /in-use/accounts/phone/888-555-1337

GET /in-use/users/email/alice@bob.com

또한 누구도 다음을 수행할 수 없습니다.

GET /in-use/users/password/dogmeat1337password에 대해 허용된 열 목록에 표시되지 않습니다.user.

여행 잘 다녀오세요.

사용자가 사용할 수 있도록 클린 헬퍼 기능을 만들었습니다.

if (!function_exists('array_has_one')) {

/**
 * array_has_one
 * 
 * Uses the search array to match at least one of the haystack to return TRUE
 * 
 * @param {array} $search
 * @param {array} $haystack
 * @return {boolean}
 */
function array_has_one(array $search, array $haystack){
    if(!count(array_intersect($search, $haystack)) === FALSE){
        return TRUE;
    }else{
        return FALSE;
    }

}
}

이런 걸 쓰면

if(array_has_one([1,2,3,4,5], [5,6,7,8,9])){
  echo "FOUND 5";
}

언급URL : https://stackoverflow.com/questions/523796/checking-to-see-if-one-arrays-elements-are-in-another-array-in-php

반응형