0

Here is a snippet of my array that is used in php 5.3.x :

$arr[$category][$item][$attr_qty] = 3;
$arr[$category][$item][$attr_price] = 12.00;

$category are arbitrary integers, as are $item, as are $attr_qty and $attr_price.

Is there a quick way of sorting, by $attr_qty, the items in each category?

Using integers makes the code easier, but I get the feeling I will have to use associative arrays.

pradeepcep
  • 713
  • 2
  • 7
  • 20
Barny
  • 23
  • 6
  • using an associative array + something like [Sort PHP multi-dimensional array based on key?](http://stackoverflow.com/a/16306693/1700963) might work for what you need? – Class Dec 02 '14 at 03:33
  • Found the solution and it is called a wrapped reusable function with extra arguments - http://stackoverflow.com/questions/8230538/pass-extra-parameters-to-usort-callback function - function fsort_subarray( &$arr, $index, $dir ) { usort( &$arr, function( $a, $b ) use ( $index, $dir ) { if((int)$dir == 0) { return ( $a[$index] > $b[$index]); } else { return ( $a[$index] < $b[$index]); } }); } – Barny Dec 02 '14 at 04:17

1 Answers1

0

You can use usort which allows you to specify a custom sorting function

usort($arr, 'customSortFunction');

function customSortFunction($a, $b)
{
    if     ($a['item']['attr_qty'] > $b['item']['attr_qty']) return 1;  //First element is bigger
    elseif ($a['item']['attr_qty'] < $b['item']['attr_qty']) return -1; //Second element is bigger
    else return 0;  //Both are equal
}
Manmaru
  • 578
  • 3
  • 8