Reputation: 325
/ Begin Updates /
The below solutions will work if I target a single array of arrays but not the array of arrays of arrays.
This is only a chunk of the associative array, each grouped piece will need to be sorted. See updated array.
I've tried the following and it doesn't hit the subarray it seems:
function natorder($a, $b){
return strnatcmp( $a['name'], $b['name'] );
}
usort($array, 'natorder');
/ End of Updates /
Trying variations usort
, sort
and the following function:
function sortNames($a, $b){
return $a['name'] - $b['name'];
}
I am unable to sort my array:
[abc-abc] => Array
(
[0] => Array
(
[name] => abc-abc-34
[qty] => 4
[sub_qty] => 4
[area] => G11
)
[1] => Array
(
[name] => abc-abc-45
[qty] => 145
[sub_qty] => 146
[area] => G11
)
[2] => Array
(
[name] => abc-abc-67
[qty] => 215
[sub_qty] => 100,
116
[area] => T,
G12
)
[3] => Array
(
[name] => abc-abc-56
[qty] => 0
)
)
[def-def] => Array
(
[0] => Array
(
[name] => def-def-34
[qty] => 4
[sub_qty] => 4
[area] => G11
)
[1] => Array
(
[name] => def-def-45
[qty] => 145
[sub_qty] => 146
[area] => G11
)
[2] => Array
(
[name] => def-def-56
[qty] => 0
)
)
To the following:
[abc-abc] => Array
(
[0] => Array
(
[name] => abc-abc-34
[qty] => 4
[sub_qty] => 4
[area] => G11
)
[1] => Array
(
[name] => abc-abc-45
[qty] => 145
[sub_qty] => 146
[area] => G11
)
[2] => Array
(
[name] => abc-abc-56
[qty] => 0
)
[3] => Array
(
[name] => abc-abc-67
[qty] => 215
[sub_qty] => 100,
116
[area] => T,
G12
)
)
[def-def] => Array
(
[0] => Array
(
[name] => def-def-34
[qty] => 4
[sub_qty] => 4
[area] => G11
)
[1] => Array
(
[name] => def-def-45
[qty] => 145
[sub_qty] => 146
[area] => G11
)
[2] => Array
(
[name] => def-def-56
[qty] => 0
)
)
Do I need to account for the additional keys not present in abc-abc-56
? Is there an alternate tool or function I should be using?
The name will always have the format of 3 letters, a dash, followed by 3 letters but after that it varies with other characters and numbers. So it could be:
abc-abc-1, abc-abc1, abc-abc.1, or abc-abc_1
but I'm most concerned with the first pattern being sorted correctly.
Your review is much appreciated!
Upvotes: 2
Views: 100
Reputation: 163362
If you have a multi dimensional array, you could use array_map and use usort in the callback function.
In the callback of usort use strnatcmp.
For example:
$array = array_map(function($x){
usort($x, function($a, $b){
return strnatcmp($a['name'], $b['name']);
});
return $x;
}, $array);
For the single array with multiple names you could use:
function sortNames($a, $b)
{
return strnatcmp($a['name'], $b['name']);
}
usort($array, "sortNames");
print_r($array);
Upvotes: 1