efficient way to search object in an array by a property

前端 未结 7 1485
傲寒
傲寒 2020-12-29 12:36

well, having something like:

$array[0]->id = \'one\';
$array[0]->color = \'white\';
$array[1]->id = \'two\';
$array[1]->color = \'red\';
$array[2         


        
相关标签:
7条回答
  • 2020-12-29 13:15

    Something I like to do in these situations is to create a referential array, thus avoiding having to re-copy the object but having the power to use the reference to it like the object itself.

    $array['one']->id = 'one';
    $array['one']->color = 'white';
    $array['two']->id = 'two';
    $array['two']->color = 'red';
    $array['three']->id = 'three';
    $array['three']->color = 'blue';
    

    Then we can create a simple referential array:

    $ref = array();
    foreach ( $array as $row )
        $ref[$row->id] = &$array[$row->id];
    

    Now we can simply test if an instance exists in the array and even use it like the original object if we wanted:

    if ( isset( $ref['one'] ) )
        echo $ref['one']->color;
    

    would output:

    white
    

    If the id in question did not exist, the isset() would return false, so there's no need to iterate the original object over and over looking for a value...we just use PHP's isset() function and avoid using a separate function altogether.

    Please note when using references that you want use the "&" with the original array and not the iterator, so using &$row would not give you what you want.

    0 讨论(0)
提交回复
热议问题