PHP:我怎么能排序和筛选的"阵列和QUOT ;,这是一个对象,实施了ArrayAccess? [英] PHP: how can I sort and filter an "array", that is an Object, implementing ArrayAccess?

查看:222
本文介绍了PHP:我怎么能排序和筛选的"阵列和QUOT ;,这是一个对象,实施了ArrayAccess?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,该对象是对象的集合,行为像阵列。这是一个数据库结果对象。类似如下:

I have an object that is a collection of objects, behaving like an array. It's a database result object. Something like the following:

$users = User::get();
foreach ($users as $user)
    echo $user->name . "\n";

$用户变量是一个实现对象 ArrayAccess接口 可数 接口。

The $users variable is an object that implements ArrayAccess and Countable interfaces.

我想排序和过滤这种阵,但我不能用它阵列功能:

I'd like to sort and filter this "array", but I can't use array functions on it:

$users = User::get();
$users = array_filter($users, function($user) {return $user->source == "Twitter";});
=> Warning: array_filter() expects parameter 1 to be array, object given

如何的我可以的排序和过滤这种类型的对象?

How can I sort and filter this kind of object?

推荐答案

这是可能的,但效果并不理想。我看到人们在某种程度上认为它不能做,只是因为系统(PHP)是这样设计的。但是,你的老板或你的用户并不关心。你不能说你的用户:对不起你们,我不能给你这个功能,因为array_filter预计一个数组,但我的用户是一个集合对象

It's possible, but not ideal. I see that people somehow think that it can't be done, just because the system (PHP) was designed this way. But your boss or your users don't care. You can't say to your users: "sorry guys, I can't give you this feature because the array_filter expects an array, but my users are in a Collection object".

我将修改你的榜样。

$users = User::get();
$users = toArrayShallow($users);
$users = array_filter($users, function($user) {return $user->source == "Twitter";});

function toArrayShallow($data) {
    $output = array();
    foreach ($data as $item)
        $output[] = $item;
    return $output;
}

就是这样。 只是一个额外的行并一个辅助的功能!
不足之处是在 $用户变量不再是一个对象,但一个数组。幸运的是,它是对象的数组,这样你就保留大部分的功能​​。

That's it. Just one extra line and a helper function! The downside is that the $users variable is no longer an object, but an array. Luckily, it's an array of objects, so you do retain much of the functionality.

这篇关于PHP:我怎么能排序和筛选的"阵列和QUOT ;,这是一个对象,实施了ArrayAccess?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆