Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 680
Jane Panda Avatar asked Dec 10 '10 03:12

Jane Panda


1 Answers

Only way I can think of that doesn't involve iterating the array for each search (see Jacob's answer) is to store references to each item in two arrays.

Edit: As the URLs and IDs cannot collide, they may be stored in the same reference array (thanks Matthew)

$items; // array of item objects
        // Use objects so they're implicitly passed by ref

$itemRef = array();

foreach ($items as $item) {
    $itemRef[$item->unique_id] = $item;
    $itemRef[$item->url] = $item;
}

// find by id
$byId = $itemRef[$id];

// find by url
$byUrl = $itemRef[$url];

You could probably encapsulate this nicely using a collection class that implements getById() and getByUrl(). Internally, it could store the references in as many arrays as is necessary.

Of course, what you're essentially doing here is creating indexed result sets, something best left to database management systems.

like image 72
Phil Avatar answered Oct 17 '22 04:10

Phil