开发者

Sort MultiDimensional Array created By Object Class by multiple keys

What I'd like to do is sort this multidimensional array by multiple keys. I've attempted to use array_multisort() but haven't had luck because of the type of array.

A function that can have multiple keys to it to sort by (relevancy, date) would be best so that other arrays with the same structure could use it as well.

This is the $array I'm working with:

Array
(
    [0] => DALQueryResult Object
        (
            [_results:DALQueryResult:private] => Array
                (
                    [0] => 32048
                    [id] => 32048
                    [1] => 1
                    [relevancy] => 1
                )
        )
    [1] => DALQueryResult Object
        (
            [_results:DALQueryResult:private] => Array
                (
                    [0] => 32002
                    [id] => 32002
                    [1] => 1
                    [relevancy] => 1
                )
        )
    [2] => DALQueryResult Object
        (
            [_results:DALQueryResult:private] => Array
                (
                    [0] => 31921
                    [id] => 31921
                    [1] => 1
                    [relevancy] => 1
                )
        )
    [3] => DALQueryResult Object
        (
            [_results:DALQueryResult:private] => Array
                (
                    [0] => 31868
                    [id] => 31868
                    [1] => 1
                    [relevancy] => 1
                )
        )
    [4] => DALQueryResult Object
        (
            开发者_如何学运维[_results:DALQueryResult:private] => Array
                (
                    [0] => 31811
                    [id] => 31811
                    [1] => 1
                    [relevancy] => 1
                )
        )
)

I've tried this function (found here), but haven't had luck:

$sort = array();
foreach($array as $k=>$v) {
    $sort['relevancy'][$k] = $v['relevancy'];
    $sort['date'][$k] = $v['date'];
}
# sort by event_type desc and then title asc
array_multisort($sort['relevancy'], SORT_DESC, $sort['date'], SORT_DESC, $array);

After running array_multisort function I see this:

Fatal error: Cannot use object of type DALQueryResult as array


I take it you are using code that can be found here. If so, just modify your SQL query with:

ORDER BY relevancy, date

In your case it doesn't work because DALQueryResult is not an array, so $v['relevancy'] will cause an error (it should be $v->relevancy). Even if you changed it, it wouldn't work because DALQueryResult is an object, not an array (and it doesn't implement ArrayAccess either).

I'd also suggest you use PDO instead of a random class found on the web (if that's the case, of course). :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜