Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multidimensional array to single array sort by value

I have one multidimensional array and this array I have to convert into single array with sort. I tried to use call_user_func_array('array_merge', $ranges); this function. After using this function get single array. When I use sort() function on single array then show output 1.

My array

    Array
(
    [range1] => Array
        (
            [0] => 1113
            [1] => 2224 
        )

    [range2] => Array
        (
            [0] =>  500
            [1] => 1112
        )

    [range3] => Array
        (
            [0] => 2225
            [1] => 4446
        )
)

Use call_user_func_array('array_merge', $ranges); output

    Array
(
    [0] => 1113
    [1] => 2224 
    [2] =>  500
    [3] => 1112
    [4] => 2225
    [5] => 4446
)

Now I am use sort() function then show 1. Why this happen?

like image 868
sandip kakade Avatar asked May 07 '26 15:05

sandip kakade


2 Answers

You're almost there. In sort() function, array is passed by reference, and return true on success and false on failure. So you should apply sort() function on the flattened array like this:

$array = call_user_func_array('array_merge', $ranges);
sort($array);

// display sorted array
var_dump($array);

Here's the reference:

  • http://php.net/manual/en/function.sort.php
like image 80
Rajdeep Paul Avatar answered May 09 '26 03:05

Rajdeep Paul


sort() function work by reference and returning true or false so no need to asign result to variable because source variable is changed by reference

like image 43
rafwlaz Avatar answered May 09 '26 04:05

rafwlaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!