如何通过键的值对带有stdClass对象的多维数组进行排序? [英] How do I sort a multidimensional array with stdClass Objects by values of a key?
本文介绍了如何通过键的值对带有stdClass对象的多维数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是的,我已经搜索并尝试了许多技术,但是似乎没有任何效果.这是我的数组:
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
)
)
我基本上想按名称键对此进行排序,但是我在Stackoverflow上尝试过的每个功能似乎都无法正常工作,因为我得到了一个没有错误的空白页面.
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.
我尝试过:
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');
但这没用.
有什么想法吗?
推荐答案
您几乎是对的,但是$row[$col]
试图像数组一样访问对象.您需要类似$row->{$col}
的名称.这是一个更简单的工作示例:
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);
输出:
Array
(
[0] => stdClass Object
(
[name] => Business1
)
[1] => stdClass Object
(
[name] => Business2
)
[2] => stdClass Object
(
[name] => Business3
)
)
这篇关于如何通过键的值对带有stdClass对象的多维数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文