1

I have been tried couple of times before asking here, i've also seen this question

which is similar to mine but unfortunatly it doesnt work (or i can get it working as well).

I have an array like this:

    Array (

  [user_1] => Array 
            (
              [0] => Array
                (
                  [category] => string_var
                  [time] => unix_timestamp 
                ),
              [1] => Array
                (
                  [category] => string_var
                  [time] => unix_timestamp 
                ),
              [2] => Array
                (
                  [category] => string_var
                  [time] => unix_timestamp 
                )
            ),

  [user_2] => Array 
            (
              [0] => Array
                (
                  [category] => string_var
                  [time] => unix_timestamp 
                ),
              [1] => Array
                (
                  [category] => string_var
                  [time] => unix_timestamp 
                ),
              [2] => Array
                (
                  [category] => string_var
                  [time] => unix_timestamp 
                )
            )
      )

And for each user i have to sort the 2nd-level array by timestamp.

Hence, i've tried:

foreach ($array as $user => $user_data) {

    timestamps = array();

    foreach($user_data as $key => $actual_data) {
       $timestamps[$key] = $actual_data['time'];
    }
    array_multisort($timestamps, SORT_ASC, $user_data);
}

unset($timestamps);
print_r($array); // the original array should now be sorted by timestamp

Well, no sorting happens, the final array is exactly = the original one.

NOTES :

  • the key ['time'] into the 2nd-level array comes from a MYSQL column and it's stored as BIGINT. var_dump gives me: int(1432587949), so it shouldnt be a variable type issue
  • i have also tried usort, with the same result: no sorting.

Where am i wrong? thanks

Community
  • 1
  • 1
sciakysystem
  • 97
  • 1
  • 9

1 Answers1

1

You want to do something like this:

array_walk($array, function(&$arr) {usort($arr, function($a,$b){return ($a["time"] < $b["time"]) ? -1 : ($a["time"] > $b["time"] ? 1 : 0);});});

But since you said that the data come from a database then I suggest you sort them there because it's likely to be faster than sorting it in php.

hynner
  • 1,332
  • 1
  • 10
  • 20