Laravel按键排序对象

时间:2017-09-11 01:06:56

标签: php laravel sorting

我有以下内容,我想通过按字母顺序排序,即每个数组的第一个是" bname",然后是" created_at"。

{
    "leads": [
        {
            "lead_id": 1,
            "zoho_lead": null,
            "bname": "ABC Limited",
            "tname": "ABC",
            "source_id": 11,
            "industry_id": 1,
            "user_id": 1,
            "created_at": "2017-09-06 15:54:21",
            "updated_at": "2017-09-06 15:54:21",
            "user": "Sean McCabe",
            "source": "Unknown",
            "industry": "None"
        },
        {
            "lead_id": 2,
            "zoho_lead": 51186111981,
            "bname": "Business Name Limited",
            "tname": "Trading Name",
            "source_id": 11,
            "industry_id": 1,
            "user_id": 1,
            "created_at": "2017-06-01 12:34:56",
            "updated_at": null,
            "user": "John Doe",
            "source": "Unknown",
            "industry": "None"
        }
    ]
}

我试图在foreach循环中使用kso​​rt:

class LeadController extends Controller
{
    use Helpers;

    public function index(Lead $leads)
    {
        $leads = $leads->all();

        foreach($leads as $key => $lead){
            $lead->user = User::where('id', $lead->user_id)->first()->name;
            $lead->source = Source::where('id', $lead->source_id)->first()->name;
            $lead->industry = Industry::where('id', $lead->industry_id)->first()->name;

            $lead->ksort();
        }

        return $leads;
    }

但是我收到以下错误:

Call to undefined method Illuminate\\Database\\Query\\Builder::ksort()

我如何使用此功能,或者是否有Laravel方式这样做,或者更好的方式?

感谢。

2 个答案:

答案 0 :(得分:1)

管理以按字母顺序返回密钥,因此以下是其他人应该要求的解决方案:

public function index(Lead $leads)
{
    $leadOut = Array();

    $leads = $leads->all();

    foreach($leads as $key => $lead){
        $lead->user = User::where('id', $lead->user_id)->first()->name;
        $lead->source = Source::where('id', $lead->source_id)->first()->name;
        $lead->industry = Industry::where('id', $lead->industry_id)->first()->name;

        //Convert to Array
        $leadOrder = $lead->toArray();
        //Sort as desired
        ksort($leadOrder);
        //Add to array
        $leadOut[] = $leadOrder;
    }

    return $leadOut;
}

有一种更简洁的方法可以做到这一点,但它适用于我的实例,也许可能会发布更好的其他答案。

答案 1 :(得分:0)

您可以执行以下操作:

return Lead::with('user', 'source', 'industry')->get()->map(function ($lead) {

        $item = $lead->toArray();

        $item['user'] = $lead->user->name;
        $item['source'] = $lead->source->name;
        $item['industry'] = $lead->industry->name;

        ksort($item);

        return $item;
    });

这应该更有效率,因为它会急切加载关系,而不是为每次迭代进行3次额外查询。