Thursday, 3 July 2014

array search

function findWhere($array, $matching) {
    foreach ($array as $item) {
        $is_match = true;
        foreach ($matching as $key => $value) {

            if (is_object($item)) {
                if (! isset($item->$key)) {
                    $is_match = false;
                    break;
                }
            } else {
                if (! isset($item[$key])) {
                    $is_match = false;
                    break;
                }
            }

            if (is_object($item)) {
                if ($item->$key != $value) {
                    $is_match = false;
                    break;
                }
            } else {
                if ($item[$key] != $value) {
                    $is_match = false;
                    break;
                } 
            }
        }

        if ($is_match) {
            return $item;   
        }
    }

    return false;
}
Example:
$cars = array(
    array('id' => 1, 'name' => 'Toyota'),
    array('id' => 2, 'name' => 'Ford')
);

$car = findWhere($cars, array('id' => 1));
or

$car = findWhere($cars, array(
    'id' => 1,
    'name' => 'Toyota'
));

No comments:

Post a Comment