Bob Bob - 5 months ago 8
PHP Question

Reference PHP array by multiple indexes

This may be some sort of weird longer shortcut, and please correct me if I'm mistaken in this train of thought...

I have a matrix of data that looks like:

unique_id | url | other random data...
unique_id | url | other random data...
unique_id | url | other random data...


I want to be able to reference an item by either it's url, or it's unique_id - is there a fancy way to do this?

I suppose the cheating solution would be to just make two arrays, but I was wondering if there is a better way.

Answer

Try something like this:

function selectByIdOrURL($array, $data) {
    foreach($array as $row) {
       if($row['unique_id'] == $data || $row['url'] == $data) return $row;
    }
    return NULL;
}

$array = array(
           array('unique_id' => 5, 'url' => 'http://blah.com'),
           array('unique_id' => 3, 'url' => 'http://somewhere_else.com')
         );
$found = selectByIdOrURL($array, 5); //array('unique_id' => 5, 'url' => 'http://blah.com')
$nfound = selectByIdOrURL($array, 10); //NULL