views:

48

answers:

3

Suppose I have an array that mimics a dayabase table. Each array element reporesents a row and within each row is another array that contains the field names and values.

Array
(
    [0] => Array
        (
            [name] => Sony TV
            [price] => 600.00
        )

    [1] => Array
        (
            [name] => LG TV
            [price] => 350.00
        )

    [2] => Array
        (
            [name] => Samsung TV
            [price] => 425.00
        )  
}

What I want to do is sort the rows (outer array elements) by price. Below is an example of what I want to achieve:

Array
(
    [0] => Array
        (
            [name] => LG TV
            [price] => 350.00
        )

    [1] => Array
        (
            [name] => Samsung TV
            [price] => 425.00
        )

    [2] => Array
        (
            [name] => Sony TV
            [price] => 600.00
        )        
}

As you can see I don't need to preserve the keys of the outer array.

+1  A: 

You can use the usort function with a callback

http://www.php.net/manual/en/function.usort.php

Vals
+3  A: 

You can use usort():

function sort($a, $b) {
    if ($a['price'] == $b['price']) return 0;
    return ($a['price'] > $b['price']) ? 1 : -1;
}

usort($array, 'sort');

Even better if you create a class like this to reuse the code:

class FieldSorter {
    public $field;

    function __construct($field) {
        $this->field = $field;
    }

    function cmp($a, $b) {
        if ($a[$this->field] == $b[$this->field]) return 0;
        return ($a[$this->field] > $b[$this->field]) ? 1 : -1;
    }
}

$sorter = new FieldSorter('price');    
usort($array, array($sorter, "cmp"));

This way, you can easily sort by other fields.

And although you said the the keys of the outer array don't have to be preserved you can easily achieve this by using uasort() instead of usort.

Felix Kling
+4  A: 

You need to use usort, a function that sorts arrays via a user defined function. Something like:

function cmp($a, $b)
{
    if ($a["price"] == $b["price"]) {
        return 0;
    }
    return ($a["price"] < $b["price"]) ? -1 : 1;
}

usort($yourArray,"cmp")
Dancrumb