0

I have a big array with child array with child arrays on it.

The scheme is like this:

$bigArray['apple'][]  = array('shop1', 'Fruit', '7');
$bigArray['apple'][]  = array('shop2', 'Fruit', '5');
$bigArray['pear'][]   = array('shop2', 'Fruit', '3.5');
$bigArray['banana'][] = array('shop1', 'Fruit', '2');

So in this case $bigArray['apple'] contains 2 arrays.

First thing is, I want to sort this arrays from the 3rd parameter(price) in ascending order (lowest price to highest price) So when printed it will display:

'shop2', 'Fruit', '5' ->lowest price
'shop1', 'Fruit', '7'

Second thing is, I want to sort the entire array $bigArray in ascending order (lowest price to highest price again); Now since arrays like $bigArray['apple'] are already sorted, in the $bigArray sort only $bigArray['apple'][0] first array will be taken into consideration because [0] will be the lowest price of this child array, already sorted. So in the end when printed $bigArray will display:

'shop1', 'Fruit', '2'
'shop2', 'Fruit', '3.5'
'shop2', 'Fruit', '5'
....

I have been struggling with usort but is far more complicated for me to work with multidimensional associative arrays.

Thank you.

inrob
  • 4,969
  • 11
  • 38
  • 51

1 Answers1

1

I think that's the solution for what you want to achieve:

<?php

$bigArray['apple'][]  = array('shop1', 'Fruit', '7');
$bigArray['apple'][]  = array('shop2', 'Fruit', '5');
$bigArray['pear'][]   = array('shop2', 'Fruit', '3.5');
$bigArray['banana'][] = array('shop1', 'Fruit', '2');



foreach ($bigArray as &$item)  {

    uasort($item, function($a, $b) {        
        if ($a[2] == $b[2]) {
            return 0;
        }    

        return ($a[2] < $b[2]) ? -1 : 1;    

    });
}

uasort($bigArray, function($a, $b) { 
    if ($a[0][2] == $b[0][2]) {
        return 0;
    }    

    return ($a[0][2] < $b[0][2]) ? -1 : 1;    
});

foreach ($bigArray as $k => $v) {

    foreach ($v as $item)
    {
        echo $k.': '.$item[0].' '.$item[1].' '.$item[2]."<br />";            
    }

}
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291