John Davidson

Sort multi-dimentional inner array PHP

0 comments
Message:


I have been trying to sort multi-dimensional inner array, i have tried array_multisort() method but doesn't worked in my case.


$array = [
[
'sizes'=>[
[
'weight'=>25,
'height'=>110
], [
'weight'=>45,
'height'=>110
],

]
],
[
'sizes'=>[
[
'weight'=>80,
'height'=>120
],[
'weight'=>20,
'height'=>120
]
]

]
];

I need to sort the above array based on weight in such a way that if sort by highest weight array should return sizes block with highest weight and vice-versa. In this case "weight": 80 is the highest and if sort by lowest 1st "weight": 20 should come 1st.


Expected output after sort for both SORT_ASC and SORT_DESC


 $array = [
[
'sizes'=>[
[
'weight'=>80,
'height'=>120
],[
'weight'=>20,
'height'=>120
]
]

],
[
'sizes'=>[
[
'weight'=>25,
'height'=>110
], [
'weight'=>45,
'height'=>110
],

]
]
];


My Answer:
You can achieve the desired sorting by using a custom sorting function with the usort() function in PHP. Here is an example code snippet to sort the inner arrays based on the 'weight' key:

php
usort($array, function($a, $b) {
$weightA = max(array_column($a['sizes'], 'weight'));
$weightB = max(array_column($b['sizes'], 'weight'));

return $weightA <=> $weightB;
});

// For SORT_DESC, change the comparison to $weightB <=> $weightA

print_r($array);


This code snippet will sort the $array based on the highest 'weight' value in the 'sizes' sub-array. You can change the comparison to sort in descending order.

Rate this post

4 of 5 based on 9786 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us