PHP
Format : $salesData["suppliers"][$supplierkey]['sales'][$salesPeriod]['sales']
I want to sort (desc):
The key $salesData["suppliers"][$supplierkey]
by the numerical value populated in $salesData["suppliers"][$supplierkey]['sales'][0]['cost']
So the following example:
$salesData["suppliers"][Dong]
$salesData["suppliers"][Ding]
Would be changed to:
$salesData["suppliers"][Ding]
$salesData["suppliers"][Dong]
Because
$salesData["suppliers"][Ding][sales][0][cost] = 231.0600
$salesData["suppliers"][Dong][sales][0][cost] = 92.8900
Is it possible to do it on multidimension arrays? I assume I need to use array_multisort
somehow?
Any advise would be appreciated
[
{
suppliers: {
Dong: {
ID: 3663313744756234943,
sales: [
{ cost: 92.8900, sales: 180.869565 },
{ cost: 12.9900, sales: 394.782609 },
{
locations: {
salesRow: 18,
costRow: 19,
GPRow: 20,
marginRow: 21,
pSalesChangeRow: 22,
pGPChangeRow: 23,
ptotalSalesRow: 24,
ptotalGPRow: 25,
},
},
],
},
Ding: {
ID: 3678436471493790070,
sales: [
{ cost: 231.0600, sales: 95.565217 },
{ cost: 26.8200, sales: 85.130435 },
{
locations: {
salesRow: 28,
costRow: 29,
GPRow: 30,
marginRow: 31,
pSalesChangeRow: 32,
pGPChangeRow: 33,
ptotalSalesRow: 34,
ptotalGPRow: 35,
},
},
],
},
},
},
]
The other examples on this site show 1 level down sorting but not multi levels down.
I tried :
Foreach($salesData["suppliers"] as $supplierkey=>$id) {
$keys = array_column($salesData["suppliers"], 'cost');
array_multisort($keys, SORT_ASC, $new);
var_dump($new);
die();
}
but it provides an error I don’t think I am getting :’cost’ right?
2
Answers
This should be easy. 1st you store all the
costs
in an array and then sort thatcosts
array. Now reorder the mainsuppliers
array based on the sortedcosts
array.Something like the following:
You can use
uasort
to define yourself the sorting condition and to keep the named keys of your array.demo
Note that you have to use a reference in the
foreach
loop (otherwise you will sort only a copy of your item and not the item itself in your array).