Peeyush Kushwaha
Peeyush Kushwaha

Reputation: 3623

PHP: search for a value in an array which contains objects

what i am looking for is a fast way to search up anything from these and get all fields back, for example if i search the sample code (given below) for "red" in favcolors, i get back name of the person whose kid's fave color this is, i.e. in this case, return an array containing jhon and homer. if the search term is for people with age = 43 then return homer, and so on...:

<?php
class person {
public $name;
public $kidsfavcolors=array();
public $age;
}

$people['jhon'] = new person;
$people['jhon']->name = "jhon";
$people['jhon']->age = 30;
$people['jhon']->kidsfavcolors['katherine']= "red";
$people['jhon']->kidsfavcolors['jimmy']= "yellow";

$people['homer'] = new person;
$people['homer']->name = "homer";
$people['homer']->age = 43;
$people['homer']->kidsfavcolors['bart']= "black";
$people['homer']->kidsfavcolors['lisa']= "red";

Upvotes: 0

Views: 6468

Answers (1)

ddinchev
ddinchev

Reputation: 34673

This could be a starting point:

function search_objects($objects, $key, $value) { // might contain bugs as I typed in in SO on the go
    $return = array();
    foreach ($objects as $object) {
        $objVars = get_object_vars($object);
        if (isset($objVars[$key]) && $objVars[$key] == $value) {
           $return[] = $object;
        }
    }
    return $return;
}

print_r(search_object($people, 'name', 'john'));

Without some kind of indexing it wont be much faster then linear walk of the objects. The complexity of this search is n*(avarage properties count). You will have to modify it to search in properties that are not simple key=>value but arrays. You might want to use reflections.

Where does the data come from? I'm rather optimistic there is a much better way to do this if we know more.

Upvotes: 3

Related Questions