1

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Also possible for converting array<>object: json_decode(json_encode($all_data_array), 0);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.