efficient way to search object in an array by a property

前端 未结 7 1555
傲寒
傲寒 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

    The thing with performance of data structures is not only how to get but mostly how to store my data.

    If you are free to design your array, use an associative array:

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

    Finding is then the most cheap: $one = $array['one];

    UPDATE:

    If you cannot modify your array constitution, you could create a separate array which maps ids to indexes. Finding an object this way does not cost any time:

    $map['one'] = 0;
    $map['two'] = 1;
    $map['three'] = 2;
    ...
    

    getObjectById() then first lookups the index of the id within the original array and secondly returns the right object:

    $index = $map[$id];
    return $array[$index];
    

提交回复
热议问题