tags:

views:

67

answers:

3

I am looking to go from:

array($ID => array (name => $name, created => $timestamp))

e.g

[5632][name] = martin
[5632][created] = 131232342
[6742][name] = paul
[6742][created] = 131232312
[6321][name] = peter
[6321][created] = 131232311

to an array of ids ordered by creation like

[0] = 6321
[1] = 6742
[2] = 5632

What is the fastest way to achieve such in PHP?

+3  A: 
function sort_by_date($a, $b)
{
  if ($a['created'] == $b['created']) return 0;
  return ($a['created'] < $b['created']) ? -1 : 1;
}

$array = array(...);
uasort($array, "sort_by_date");
$ids = array_keys($array);

uasort lets you sort an array by using a custom function while maintaining keys. array_keys returns an array containing the keys of another array.

Daniel Vandersluis
would this be any fasterfunction sort_by_date($a, $b){ return strnatcmp($a['created'], $b['created']);}
Pablo
You could benchmark it, but my guess would be that `strnatcmp` would be slower (especially if your created keys are already numbers)
Daniel Vandersluis
You were correct. Your script managed 1 million iterations in 7 seconds on my server where as strnatcmp took around 9.
Pablo
A: 
$new_array = krsort(array_keys($your_array));
Alexander.Plutov
-1 (1) this does not work (2) you should not pass the result of a function to `ksort()` (3) `ksort()` returns a boolean
NullUserException
+1  A: 

Why go through the effort of sorting the entire array of arrays, when you just want the ids?

$times = array();
foreach ($array as $key => $item) {
    $times[$key] = $item['created'];
}
asort($times);
$ids = array_keys($times);
salathe