In this tutorial learn how to sort multiple or multidimensional arrays, array_multisort() can be used to sort many ways arrays at once, or a multi-dimensional array by one or more dimensions.
Syntax
Example 2 : Sorting case Insensitive values
Syntax
array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_DESC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... ]]] ) : bool
array_multisort() requires an array of columns, so we use the below code to perform the sorting.
one line code using a array columns using id: array_multisort (array_column($array, 'id'), SORT_ASC, $array);
one line code using a array columns using id: array_multisort (array_column($array, 'id'), SORT_ASC, $array);
Above tutorial output (live demo)<?php
$array = Array
(
0 => Array
(
'name' => 'Nakiya',
'country' => 'USA',
'id' => 3,
),
1 => Array
(
'name' => 'Taylor',
'country' => 'UK',
'id' => 2,
),
2 => Array
(
'name' => 'Jack',
'country' => 'France',
'id' => 1,
)
);
array_multisort (array_column($array, 'id'), SORT_ASC, $array);
print_r($array);
Array
(
[0] => Array
(
[name] => Jack
[country] => France
[id] => 1
)
[1] => Array
(
[name] => Taylor
[country] => UK
[id] => 2
)
[2] => Array
(
[name] => Nakiya
[country] => USA
[id] => 3
)
)
Example 2 : Sorting case Insensitive values
<?php
$array = array('nakiya', 'Jack', 'Taylor', 'huge');
$array_lowercase = array_map('strtolower', $array);
array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);
print_r($array);
?>
Above tutorial output : (live demo) Array
(
[0] => huge
[1] => Jack
[2] => nakiya
[3] => Taylor
)
How to compare two multidimensional arrays in php?
ReplyDeleteHow to search value in multidimensional array in php?
ReplyDeleteHow to count multidimensional array in php?
ReplyDelete