2

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?

2
  • Does the datasource not allow for ordering? Commented Aug 24, 2010 at 17:00
  • It does, however due to the complexity of the query I store the data in the users session when they login to my app. Commented Aug 24, 2010 at 17:55

3 Answers 3

3
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.

Sign up to request clarification or add additional context in comments.

3 Comments

would this be any faster function sort_by_date($a, $b) { return strnatcmp($a['created'], $b['created']); }
You could benchmark it, but my guess would be that strnatcmp would be slower (especially if your created keys are already numbers)
You were correct. Your script managed 1 million iterations in 7 seconds on my server where as strnatcmp took around 9.
1

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);

Comments

0
$new_array = krsort(array_keys($your_array));

1 Comment

-1 (1) this does not work (2) you should not pass the result of a function to ksort() (3) ksort() returns a boolean

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.