tags:

views:

57

answers:

2

I'm trying to sort several arrays in numerical order based on the value in their first key:

$array1[0] = '1';
$array1[1] = 'content';
$array1[2] = 'more content';

$array3[0] = '3';
$array3[1] = 'content';
$array3[2] = 'more content';

$array4[0] = '4';
$array4[1] = 'content';
$array4[2] = 'more content';

$array2[0] = '2';
$array2[1] = 'content';
$array2[2] = 'more content';

$arrays = array($array1, $array3, $array4, $array2);

foreach ($arrays as $array) {

echo $array[0] . ' ' . $array[1] . ' ' . $array[2] . '<br>';

}

That outputs the arrays in a '1, 3, 4, 2' sequence, I need them to be output thusly: '1, 2, 3, 4'. Not sure how or even if to use the ksort/asort/array_multisort functions here.

+1  A: 

Using usort you can specify your own sorting criteria on an array. This is an idea of how you could achieve what you ask for

function cmp($a, $b)
{
  if ($a == $b) {
      return 0;
  }
  return (intval($a[0]) < intval($b[0])) ? -1 : 1;
}

usort($arrays, "cmp");
acqu13sce
+2  A: 

You will need a custom comparison function that you then can use with usort or uasort:

function cmp($a, $b) {
    return intval($a[0]) - intval($b[0]);
}
usort($arrays, 'cmp');

As of PHP 5.3 you could also use an anonymous function for the comparison function:

usort($arrays, function($a, $b) { return intval($a[0]) - intval($b[0]); });

You could also use array_multisort, create an array of the keys that are to be sorted first and use it to sort the array items itself:

$keys = array();
foreach ($arrays as $array) $keys[] = intval($array[0]);
array_multisort($keys, $arrays);

Doing this prevents calling the comparing function for each pair of values that is compared as only the key values are compared.

Gumbo
I think that because the first index of the array is being specified as a string it's possibly safer to use intval() on the value first otherwise it might be doing a string comparison?
acqu13sce
@acqu13sce: Yes, you’re right. String comparison could yield to unexpected results as e.g. `"2" > "12"`.
Gumbo
LOL, this is more complicated than I thought it would be. I'm liking the array_multisort approach, never used it before tho so could you flesh it out for me a bit more, primarily the output aspect? And is the omission of a { after the foreach statement by design?
Clarissa
Actually, nevermind, I got it working using usort instead. Thanks!
Clarissa