0

I have two questions.

How can i create an array which i can add two values per index like:

$sample[0] = ("abc",10);

Second is that once i have created this array i would like to sort this array according to the 2nd value at the index.

So if i have an array like:

$sample[0] = ("abc",32);
$sample[1] = ("def",11);

The sorted result should be:

$sample[0] = ("def",11);
$sample[1] = ("abc",32);
user3760741
  • 153
  • 1
  • 9

1 Answers1

1

Answer to part one:

$sample[0] = array("abc", 10);

Answer to part two:

array_multisort($sample, SORT_NUMERIC);

Testing Environment:

<?php

$sample[0] = array("abc", 32);
$sample[1] = array("def", 11);
print_r($sample);

array_multisort($sample, SORT_NUMERIC);

echo '<br />';
print_r($sample);

?>

Output:

Array ( [0] => Array ( [0] => abc [1] => 32 ) [1] => Array ( [0] => def [1] => 11 ) ) 
Array ( [0] => Array ( [0] => def [1] => 11 ) [1] => Array ( [0] => abc [1] => 32 ) )

Warning from @Deceze: Above functionality is coincidental; correct code is:

usort($sample, function ($a, $b) { return $a[1] - $b[1]; })
t3chguy
  • 998
  • 6
  • 17