Viewed   96 times

Suppose I have an array that mimics a database table. Each array element represents 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.

 Answers

4

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")
Thursday, October 20, 2022
5
$target_flip = array_flip($target);

usort($routes, function($a, $b) use ($target_flip){
    return ($target_flip[$a['code']] < $target_flip[$b['code']]) ? -1 : 1;
});

Demo:

  • http://codepad.viper-7.com/DGDbAr

Docs:

  • http://php.net/manual/en/function.array-flip.php
  • http://php.net/manual/en/function.usort.php
  • http://php.net/manual/en/functions.anonymous.php
Monday, November 14, 2022
 
1

try this cmp function:

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

It should work.

Thursday, August 25, 2022
5

You can use usort as:

function cmp($a, $b) {
   return $a['weight'] - $b['weight'];
}

usort($arr,"cmp");
Monday, December 5, 2022
 
4

You're almost right, but $row[$col] tries to access the objects like an array. You want something like $row->{$col} instead. Here's a simpler, working example:

$db = array(
  0 => (object) array('name' => 'Business3'),
  1 => (object) array('name' => 'Business2'),
  2 => (object) array('name' => 'Business1')
);

$col  = 'name';
$sort = array();
foreach ($db as $i => $obj) {
  $sort[$i] = $obj->{$col};
}

$sorted_db = array_multisort($sort, SORT_ASC, $db);

print_r($db);

Outputs:

Array
(
    [0] => stdClass Object
        (
            [name] => Business1
        )

    [1] => stdClass Object
        (
            [name] => Business2
        )

    [2] => stdClass Object
        (
            [name] => Business3
        )

)
Friday, November 25, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :