kate_hudson kate_hudson - 4 months ago 10
PHP Question

Sorting array based on value

I have an array like so

array:2 [▼
"folder1" => array:3 [▼
1 => "d1_2.png"
2 => "d1_1.png"
3 => "d1_3.png"
]
"folder2" => array:3 [▼
0 => "d2_2.png"
1 => "d2_3.png"
3 => "d2_1.png"
]
]


What I am trying to do is sort this array based on the value. So the output should be something like this

array:2 [▼
"folder1" => array:3 [▼
0 => "d1_1.png"
1 => "d1_2.png"
2 => "d1_3.png"
]
"folder2" => array:3 [▼
0 => "d1_1.png"
1 => "d1_2.png"
2 => "d1_3.png"
]
]


All examples I have seen sort based on a key value, but I do not have keys. I have tried several sort functions but none of them seem to sort the array.

How can I sort it based on the array I have?

Thanks

Answer

There are a huge number of sorting functions in php, which can sort an array based on value or key, maintain index association and walk into child arrays.

What I think you want is the sort function, like this:

sort($array['folder1']);
sort($array['folder2']);

Or this:

foreach ($array as $key => $subarray) {
    sort($array[$key]);
}

Just keep in mind. It is not the outer array you want to sort, but its child arrays.