Reference PHP array by multiple indexes

前端 未结 4 820
暗喜
暗喜 2021-01-04 21:47

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:

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-04 22:20

    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.

提交回复
热议问题