Yes, I have searched and tried many techniques, but nothing seems to work. Here is my array:
Array
(
[0] => stdClass Object
(
[id]
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
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
)
)
usort($array, function($a, $b) {
return strcmp($a->name, $b->name);
});