简体   繁体   English

为什么此PHP代码对数组进行排序未返回正确的值?

[英]Why is this PHP code to sort an array not returning the correct value?

I have an array of products that I'm pulling from the db. 我有一系列从数据库中提取的产品。 I've verified that these are correct, using the following code: 我使用以下代码验证了这些正确性:

$unsorted_products = products::get( array( 'collection' => $collection->id ) );
die(print_r($unsorted_products));

...and the results are as I expect. ...结果如我所料。 The thing is, I need the results to basically be grouped by a parent category and category. 问题是,我需要将结果基本上按父类别和类别进行分组。 How they're sorted within each grouping, I don't care. 我不在乎它们在每个分组中的排序方式。 Given that I don't have access to change the model that is retrieving the data via SQL, I need to sort this array via PHP. 鉴于我无权更改通过SQL检索数据的模型,因此需要通过PHP对该数组进行排序。 I'm using the following code: 我正在使用以下代码:

$products = usort($unsorted_products, function ($a, $b) {
        return strcmp(
            $a->parentcategory.$a->categoryname,
            $b->parentcategory.$b->categoryname
        );
    });

...but dumping the $products array reveals that it is only holding the value 1. Any idea what I am doing wrong? ...但是转储$products数组表明它仅持有值1.知道我做错了吗? I've verified that the properties I am attempting to access do exist in each object. 我已经验证了我尝试访问的属性确实存在于每个对象中。

Thanks. 谢谢。

It sorts the input array. 它对输入数组进行排序。

From the usort manual: 从usort手册中:

Returns TRUE on success or FALSE on failure. 成功返回TRUE,失败返回FALSE。

You are doing it wrong. 你做错了。 usort doesn't return array, it returns ether true or false. usort不返回数组,它返回以太真或假。 It changes array that you pass as first parameter. 它更改您作为第一个参数传递的数组。

After your code is executed, $unsorted_products becomes sorted array. 执行代码后,$ unsorted_products成为排序数组。 Do this: 做这个:

$products = products::get( array( 'collection' => $collection->id ) );

and this: 和这个:

usort($products, function ($a, $b) {
        return strcmp(
            $a->parentcategory.$a->categoryname,
            $b->parentcategory.$b->categoryname
        );
    });

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

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