Reputation: 175
For example i have an array named $slice
like this :
Array
(
[0] => Array
(
[0] => 12
[1] => 4
[2] => 2
[3] => 8
[4] => 20
)
[1] => Array
(
[0] => 9
[1] => 7
[2] => 1
[3] => 10
[4] => 23
)
)
I want to sort array above so the output will be like this :
Array
(
[0] => Array
(
[0] => 2
[1] => 4
[2] => 8
[3] => 12
[4] => 20
)
[1] => Array
(
[0] => 1
[1] => 7
[2] => 9
[3] => 10
[4] => 23
)
)
Then i tried to use foreach and array_multisort, and when i use print_r the result is 1 for each col :
foreach ($slice1 as $col) {
$slicesort[] = array_multisort($col);
}
output :
Array
(
[0] => 1
[1] => 1
)
Upvotes: 0
Views: 1517
Reputation: 273
$slice = array(
array(12,4,8,2,10),
array(9,7,1,10,13)
);
foreach ($slice as &$arr) {
sort($arr);
}
print_r($slice);
Upvotes: 1
Reputation: 117
array_multisort return a boolean value, true for success, false otherwise.
Change your code this way:
foreach ($slice1 as $col) {
if (array_multisort($col)) {
$slicesort[] = $col;
}
}
Upvotes: 0
Reputation: 178
PHP array_multisort
, as per the documentation, is for sorting multiple or multi-dimensional arrays, in your case you don't really need it.
In your case you just need sort
, you can find the documentation here
$slicesort = array();
foreach ($slice1 as $col) {
sort($col);
$slicesort[] = $col;
}
Upvotes: 1
Reputation: 522402
array_multisort
sorts the array in place, it does not return the sorted array. You need to use it like this:
foreach ($slice1 as $col) {
array_multisort($col);
$slicesort[] = $col;
}
Having said this, array_multisort
is somewhat overkill here, and I'm not sure that you really need to create a copy of the array. This will do just fine:
foreach ($slice1 as &$col) {
sort($col);
}
This applies sort
to each array within $slice1
by reference, and thereby orders $slice1
in place.
Upvotes: 4