简体   繁体   English

如何使用键的值对stdClass对象排序多维数组?

[英]How do I sort a multidimensional array with stdClass Objects by values of a key?

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. 我基本上想要通过名称键对它进行排序,但我在Stackoverflow上尝试的每个函数似乎都不起作用,因为我得到一个没有错误的空白页面。

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? 有任何想法吗?

You're almost right, but $row[$col] tries to access the objects like an array. 你几乎是对的,但$row[$col]尝试像数组一样访问对象。 You want something like $row->{$col} instead. 你需要像$row->{$col}这样的东西。 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);
});

You should use usort ... 你应该使用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. 因此,您定义一个比较两个对象的函数(通过名称字段),然后在数组上运行usort,将函数作为第二个参数传递。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM