user2870829
user2870829

Reputation: 145

Reorder mysql results via php to prevent multiple queries

I query some data from mysql database and ordering by specific key. For example: ORDER BY param1 ASC

Now I output the data via while and mysql object. And I need to do two other queries which are the same but with different order. For example: ORDER BY param2 ASC and ORDER BY param3 ASC.

I know I could save data in multidimensional array and reorder by usort. But is there any more elegant way? For example reusing the mysql object and converting directly?

Thanks for any tips or ways to make it more simple.

Upvotes: 1

Views: 19

Answers (1)

user2870829
user2870829

Reputation: 145

I found following solution. Defining these functions:

function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
$sort_col = array();
foreach ($arr as $key => $row) {
    $sort_col[$key] = $row[$col];
}
array_multisort($sort_col, $dir, $arr);
}

function objectToArray($d) 
{
if (is_object($d)) {
    $d = get_object_vars($d);
}
if (is_array($d)) {
    return array_map(__FUNCTION__, $d);
} else {
    return $d;
}
}

Inside while I am adding entries to an array: $all_data[] = $row;

Then I can order my array and output:

$all_data_array = objectToArray($all_data); 
array_sort_by_column($all_data_array, 'param1');
print_r($all_data_array);

Upvotes: 1

Related Questions