Search code examples
phparrayssortingnumeric

Sort a flat subarray of numbers and preserve the keys


I Have the following array :

Array
(
[0] => Array
    (
        [video1] => 100
        [video2] => 100
        [video3] => 100
        [video4] => 85.3658536585
        [video5] => 100
        [video6] => 72
        [video7] => 100
        [video8] => 120
        [video9] => 100
        [video10] => 100
    )

 )

And i am using the following function to sort the array the ascending order based on value as follow :

foreach ($array[0] as $key => $val) {
    $score[$key] = $val;
}
array_multisort($score, SORT_ASC, $array);

Unfortunately, the sort function is not working as expected, the array is returned in the order of videoid, and I get the following warning.

Warning: array_multisort(): Array sizes are inconsistent


Solution

  • You don't need array_multisort. You have to use asort since $array[0] is a plain array.

    $score = $array[0];
    asort($score);