Programing

PHP-객체 배열에서 객체 속성별로 항목 찾기

lottogame 2020. 6. 19. 19:23
반응형

PHP-객체 배열에서 객체 속성별로 항목 찾기


배열은 다음과 같습니다.

[0] => stdClass Object
        (
            [ID] => 420
            [name] => Mary
         )

[1] => stdClass Object
        (
            [ID] => 10957
            [name] => Blah
         )
...

그리고라는 정수 변수가 $v있습니다.

ID속성에 $v이있는 객체가있는 배열 항목을 어떻게 선택할 수 있습니까?


배열을 반복하고 특정 레코드를 검색하거나 (한 번만 검색 가능) 다른 연관 배열을 사용하여 해시 맵을 작성합니다.

전자의 경우 이와 같은

$item = null;
foreach($array as $struct) {
    if ($v == $struct->ID) {
        $item = $struct;
        break;
    }
}

- 후자에 대한 자세한 내용은이 질문 이후 답변을 참조 여러 인덱스에 의해 참조 PHP 배열


YurkamTim 이 옳습니다. 수정 만 필요합니다 :

function ($) 다음에 "use (& $ searchedValue)"를 사용하여 외부 변수에 대한 포인터가 필요하면 외부 변수에 액세스 할 수 있습니다. 또한 수정할 수 있습니다.

$neededObject = array_filter(
    $arrayOfObjects,
    function ($e) use (&$searchedValue) {
        return $e->id == $searchedValue;
    }
);

$arr = [
  [
    'ID' => 1
  ]
];

echo array_search(1, array_column($arr, 'ID')); // prints 0 (!== false)

더 우아한 해결책을 찾았 습니다 . 질문에 적응하면 다음과 같이 보일 수 있습니다.

$neededObject = array_filter(
    $arrayOfObjects,
    function ($e) {
        return $e->id == $searchedValue;
    }
);

array_column사용 하여 다시 색인을 생성하면 여러 번 찾아야 할 경우 시간이 절약됩니다.

$lookup = array_column($arr, NULL, 'id');   // re-index by 'id'

그럼 당신은 단순히 $lookup[$id]마음대로 할 수 있습니다 .


class ArrayUtils
{
    public static function objArraySearch($array, $index, $value)
    {
        foreach($array as $arrayInf) {
            if($arrayInf->{$index} == $value) {
                return $arrayInf;
            }
        }
        return null;
    }
}

원하는 방식으로 사용하면 다음과 같습니다.

ArrayUtils::objArraySearch($array,'ID',$v);

@YurkaTim 의 작은 실수를 수정하면 솔루션이 나를 위해 작동하지만 다음을 추가합니다 use.

$searchedValue함수 내에서 사용하려면 use ($searchedValue)함수 매개 변수 뒤에 하나의 솔루션이있을 수 있습니다 function ($e) HERE.

array_filter함수는 반환 $neededObject조건이 다음과 같은 경우 에만 반환됩니다 .true

경우 $searchedValue문자열이나 정수 :

$searchedValue = 123456; // Value to search.
$neededObject = array_filter(
    $arrayOfObjects,
    function ($e) use ($searchedValue) {
        return $e->id == $searchedValue;
    }
);
var_dump($neededObject); // To see the output

$searchedValue목록을 확인 해야하는 배열 인 경우 :

$searchedValue = array( 1, 5 ); // Value to search.
$neededObject  = array_filter(
    $arrayOfObjects,
    function ( $e ) use ( $searchedValue ) {
        return in_array( $e->term_id, $searchedValue );
    }
);
var_dump($neededObject); // To see the output

I sometimes like using the array_reduce() function to carry out the search. It's similar to array_filter() but does not affect the searched array, allowing you to carry out multiple searches on the same array of objects.

$haystack = array($obj1, $obj2, ...); //some array of objects
$needle = 'looking for me?'; //the value of the object's property we want to find

//carry out the search
$search_results_array = array_reduce(
  $haystack,

  function($result_array, $current_item) use ($needle){
      //Found the an object that meets criteria? Add it to the the result array 
      if ($current_item->someProperty == $needle){
          $result_array[] = $current_item;
      }
      return $result_array;
  },
  array() //initially the array is empty (i.e.: item not found)
);

//report whether objects found
if (count($search_results_array) > 0){
  echo "found object(s): ";
  print_r($search_results_array[0]); //sample object found
} else {
  echo "did not find object(s): ";
}

Try

$entry = current(array_filter($array, function($e) use($v){ return $e->ID==$v; }));

working example here


I did this with some sort of Java keymap. If you do that, you do not need to loop over your objects array every time.

<?php

//This is your array with objects
$object1 = (object) array('id'=>123,'name'=>'Henk','age'=>65);
$object2 = (object) array('id'=>273,'name'=>'Koos','age'=>25);
$object3 = (object) array('id'=>685,'name'=>'Bram','age'=>75);
$firstArray = Array($object1,$object2);
var_dump($firstArray);

//create a new array
$secondArray = Array();
//loop over all objects
foreach($firstArray as $value){
    //fill second        key          value
    $secondArray[$value->id] = $value->name;
}

var_dump($secondArray);

echo $secondArray['123'];

output:

array (size=2)
  0 => 
    object(stdClass)[1]
      public 'id' => int 123
      public 'name' => string 'Henk' (length=4)
      public 'age' => int 65
  1 => 
    object(stdClass)[2]
      public 'id' => int 273
      public 'name' => string 'Koos' (length=4)
      public 'age' => int 25
array (size=2)
  123 => string 'Henk' (length=4)
  273 => string 'Koos' (length=4)
Henk

Way to instantly get first value:

$neededObject = array_reduce(
    $arrayOfObjects,
    function ($result, $item) use ($searchedValue) {
        return $item->id == $searchedValue ? $item : $result;
    }
);

I posted what I use to solve this very issue efficiently here using a quick Binary Search Algorithm: https://stackoverflow.com/a/52786742/1678210

I didn't want to copy the same answer. Someone else had asked it slightly differently but the answer is the same.

참고URL : https://stackoverflow.com/questions/4742903/php-find-entry-by-object-property-from-an-array-of-objects

반응형