efficient way to search object in an array by a property

前端 未结 7 1483
傲寒
傲寒 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:11

    Here is what I use. Reusable functions that loop through an array of objects. The second one allows you to retrieve a single object directly out of all matches (the first one to match criteria).

    function get_objects_where($match, $objects) {
        if ($match == '' || !is_array($match)) return array ();
        $wanted_objects = array ();
        foreach ($objects as $object) {
            $wanted = false;
            foreach ($match as $k => $v) {
                if (is_object($object) && isset($object->$k) && $object->$k == $v) {
                    $wanted = true;
                } else {
                    $wanted = false;
                    break;
                };
            };
            if ($wanted) $wanted_objects[] = $object;
        };
        return $wanted_objects;
    };
    
    function get_object_where($match, $objects) {
        if ($match == '' || !is_array($match)) return (object) array ();
        $wanted_objects = get_objects_where($match, $objects);
        return count($wanted_objects) > 0 ? $wanted_objects[0] : (object) array ();
    };
    

提交回复
热议问题