Reputation: 626
very simple but confused me! here is it:
$command[] = "30";
$command[] = "20";
$command[] = "10";
$command[] = "5";
$command[] = "1";
asort($command);
print_r($command);
return:
Array ( [0] => Array ( [0] => 30 [1] => 20 [2] => 10 [3] => 5 [4] => 1 ) )
but I want:
Array ( [0] => Array ( [0] => 1 [1] => 5 [2] => 10 [3] => 20 [4] => 30 ) )
exact code I use:
$cmd_id = array();
foreach ($_POST as $k => $v)
{
if($k=='cmd_id' && $v>0)
$cmd_id[] = $v;
}
form is multiple checkboxes:
<input type="checkbox" name="cmd_id[]" .........
Upvotes: 0
Views: 2847
Reputation: 6013
Original anwer: use arsort.
--
Update: asort is for maintaining the indexes, what you want is the normal sort(). Also, see Sorting Arrays in the php manual
--
Update 2: The issue is with how you populate your array. Instead do this:
if (!empty($_POST['cmd_id'])) {
foreach ($_POST['cmd_id') {
$cmd_id[] = intval($v); # Preferably force ints if you expect ints
}
} else { /* Handle use input failure accordingly */ }
Upvotes: 2
Reputation: 46258
Your value seems to be an array of values. I'm assuming that in your HTML, you have something like name="cmd_id[]"
in the form. Therefore, the HTTP POST variable cmd_id
will arrive to PHP in array form.
$cmd_id = array();
foreach ($_POST['cmd_id'] as $value) {
if($value > 0) {
$cmd_id[] = $value;
}
}
sort($cmd_id, SORT_NATURAL);
print_r($cmd_id);
Upvotes: 1