Comments Feed
Sep
16

Sort Multidimensional array by order of an array

Although the title of this post may sound confusing - what I achieved was an extremely useful function. Whilst building a website using SphinxSearch for some search resultsĀ  - after using MySQL to get the data I needed:

PHP retrieves a set of id's from sphinx (4,5,2,34,1,453,3)

SELECT id,name,url FROM table WHERE id IN (4,5,2,34,1,453,3);

Mysql returns it's record set in its natural order (how it's stored on disk), problem being this now looses our order from sphinx. So I made this function that accepts an array to sort, an array to order by, and a key to use to order.

/*
 *
 * @author Mark Willis
 *
 * @input $input_array - multi dimensional array to sort
 * @input $key_array - single dimensional array of values to sort by (in order)
 * @input $sort_field - the name of the $input_array column to sort by
 * @output $results - $input_array ordered by $key_array
 *
 */
    function sort_md_array_by_array($input_array,$key_array,$sort_field) {
        $results = array();
        foreach($key_array as $sort_id => $not_used) {
            foreach($input_array as $arr_data) {
                if($arr_data[$sort_field] == $sort_id) {
                    $results[] = $arr_data;
                }
            }
        }
        return $results;
    }

An example of usage would be:

$order_by = array(23,2,54,3);
$unordered_search = array(
    array("id" => 2,"data" => "test2"),
    array("id" => 3,"data" => "test3"),
    array("id" => 23,"data" => "test23"),
    array("id" => 54,"data" => "test54")
);    
 
$search_results = sort_md_array_by_array($unordered_search,$order_by, "id");
 
print_r($unordered_search); // 2,3,23,54
print_r($search_results); // 23,2,54,3
posted by Mark Willis
Tags:

One Response to “Sort Multidimensional array by order of an array”

  1. [...] my post about sorting multidimensional array's by an array of values I've now found a better way of keeping a mysql result set in order by using the ORDER BY FIELD() [...]

Leave a Reply