5

Yes, I have searched and tried many techniques, but nothing seems to work. Here is my array:

Array
(
    [0] => stdClass Object
        (
            [id] => 119
            [name] => Business3
            [start_date] => 1338789600
            [end_date] => 1354604400
        )

    [1] => stdClass Object
        (
            [id] => 153
            [name] => Business1
            [start_date] => 1338962400
            [end_date] => 1370498400
        )

    [2] => stdClass Object
        (
            [id] => 135
            [name] => Business2  
            [start_date] => 1339653600
            [end_date] => 1356937200
        )
)

I basically want to sort this by the name key, but every function I've tried on Stackoverflow doesn't seem to work, as in, I get a blank page with no error.

I tried this:

function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
    $sort_col = array();
    foreach ($arr as $key=> $row) {
        $sort_col[$key] = $row[$col];
    }

    array_multisort($sort_col, $dir, $arr);
}

array_sort_by_column(json_decode(json_encode($businesses), true), 'name');

But that didn't work.

Any ideas?

dallen
  • 2,621
  • 7
  • 37
  • 47

3 Answers3

12

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
        )

)
sczizzo
  • 3,196
  • 20
  • 28
3
usort($array, function($a, $b) {
    return strcmp($a->name, $b->name);
});
0

You should use usort...

So you define a function that compares two objects (by the name field) and then run usort on the array, passing in the function as the second argument.

Something like this:

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

usort ($my_array, "cmp");
var_dump($my_array);

Hope that helps!

Ben

Ben
  • 66,838
  • 37
  • 84
  • 108