PHP sorting multidimensional array issue

this is how my array look likes:
array(2) {
'yamaha' =>
array(2) {
'r1' =>
array(3) {
[0] =>
string(4) "2000"
[1] =>
string(4) "2001"
[2] =>
string(4) "1999"
}
'r2' =>
array(1) {
[0] =>
string(4) "2000"
}
}
'honda' =>
array(3) {
'ca-125' =>
array(2) {
[0] =>
string(4) "1996"
[1] =>
string(4) "1995"
}
'cb-1000-r' =>
array(4) {
[0] =>
string(4) "1993"
[1] =>
string(4) "1994"
[2] =>
string(4) "1995"
[3] =>
string(4) "1996"
}
'cb-1000-a' =>
array(6) {
[0] =>
string(4) "2008"
[1] =>
string(4) "2009"
[2] =>
string(4) "2010"
[3] =>
string(4) "2011"
[4] =>
string(4) "2012"
[5] =>
string(4) "2013"
}
}
}
I would like to sort it after alphabetical order. If I do aasort($myarray)
. It will sort after the first key. So I will get honda and yamaha. Which is correct, but I would like to also sort it after the type of the brand:cb-1000-r
andcb-1000-a
(alphabetically) and the year in a descending order. Can someone help me with this ? Thank you
[UPDATE]
This is my json. you can usejson_decode
{"B":{"r2":["1999","2001","2000"],"r1":["2000"]},"A":{"A1":["1996","1995"],"A3":["1993","1994","1995","1996"],"A2":["2008","2009","2010","2011","2012","2013"]}}
and I would like to get this json:
{"A":{"r1":["2000"],"r2":["2001","2000","1999"]},"B":{"A1":["1996","1995"],"A2":["2013","2012","2011","2010","2009","2008"],"A3":["1996","1995","1994","1993"]}}
Answer
Solution:
You'll need to loop through your nested arrays and sort each level of them:
$arr = json_decode('{"B":{"r2":["1999","2001","2000"],"r1":["2000"]},"A":{"A1":["1996","1995"],"A3":["1993","1994","1995","1996"],"A2":["2008","2009","2010","2011","2012","2013"]}}', true);
ksort($arr);
foreach ($arr as &$arr1) {
ksort($arr1);
foreach ($arr1 as &$arr2) {
rsort($arr2);
}
}
var_dump($arr);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: composer detected issues in your platform: your composer dependencies require a php version ">= 8.0.2".
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.