Sort array based on key value

I have an array like below

Array
(
[6] => Array
    (
        [name] => Extras
        [total_products] => 0
        [total_sales] => 0
        [total_affiliation] => 0
    )

[5] => Array
    (
        [name] => Office Products
        [total_products] => 7
        [total_sales] => 17
        [total_affiliation] => 8
    )

[1] => Array
    (
        [name] => Hardware Parts
        [total_products] => 6
        [total_sales] => 0
        [total_affiliation] => 0
    )

)

Now, order: Extra, Office Products, Equipment Parts

I want to sort the main array so that it is ordered by total_sales of the internal array in desc order

so the order will be: Office Products, Extras, Hardware Parts

Any help guys

+5
source share
3 answers

PHP 5.3:

usort($array, function ($a, $b) { return $b['total_sales'] - $a['total_sales']; });

PHP 5.2 -:

usort($array, create_function('$a,$b', 'return $b["total_sales"] - $a["total_sales"];'));
+12
source

Here is a class that you can use to sort with multiple sizes

Note. You must have PHP5

class MultiDimensionSort
{
    const ASCENDING = 0,DESCENDING = 1;

    public  $sortColumn,$sortType;

    public function __construct($column = 'price', $type = self::ASCENDING)
    {
        $this->column = $column;
        $this->type = $type;
    }

    public function cmp($a, $b)
    {
        switch($this->type)
        {
            case self::ASCENDING:
                return ($a[$this->column] == $b[$this->column]) ? 0 : (($a[$this->column] < $b[$this->column]) ? -1 : 1);
            case self::DESCENDING:
                return ($a[$this->column] == $b[$this->column]) ? 0 :(($a[$this->column] < $b[$this->column]) ? 1 : -1);
            default:
                assert(0); // unkown type
        }
    }
}

Just as you have an array called summary with the contents above the array. than you can sort by following the instructions. // Assuming your array variable$summary

$s = new MultiDimensionSort('total_sales', MultiDimensionSort::DESCENDING); // sort by total_sales

usort($summary, array($s, 'cmp'));
print"<pre>";print_r($summary);

! , .

+2

Use a custom function and usort:

<?php
function custom_sale_sort($a, $b)
{
    if ($a['total_sales'] < $b['total_sales'])
        return 1;
    elseif ($a['total_sales'] == $b['total_sales'])
        return 0;
    else
        return -1;
}

usort($array, 'custom_sale_sort');

If you need your array sorted in the other direction, then switch the values (1,-1)in a custom function.

+1
source

All Articles