将查询结果附加到现有的json对象

时间:2017-01-24 10:31:18

标签: php json laravel object laravel-5.3

我在2个变量中得到2个查询的结果,我有一个JSON个对象,我希望append查询结果到该JSON,然后将其返回给用户

在may控制器中我得到了所有结果

if ($request->wantsJson()) {

    $agent_id = $request->user()->id;

    $drivers_cout = Driver::all()->count();

    $drivers_cout_by_agent = Driver::where(['agent_id' => $agent_id])->get()->count();

    return $request->user();
}

//the result of  $request->user();

  #attributes: array:12 [
    "id" => 201702
    "name" => "Agent"
    "email" => "agent@gmail.com"
    "phone_number" => "966355826"
  ]

//and i want something like

  #attributes: array:12 [
    "id" => 201702
    "name" => "Agent"
    "email" => "agent@gmail.com"
    "phone_number" => "966355826"
    "drivers_count" => "96"                        //How do i append these two
    "drivers_cout_by_agent" => "16"         
  ]

谢谢

3 个答案:

答案 0 :(得分:2)

将数据添加到数组只是将数据放入具有您希望它具有的索引名称的数组中

if ($request->wantsJson()) {

    $agent_id = $request->user()->id;              

    $drivers_count = Driver::all()->count();         //<-- fixed spelling

    $drivers_cout_by_agent = Driver::where(['agent_id' => $agent_id])->get()->count();

    $arr = $request->user();
    $arr['drivers_count'] = $drivers_count;
    $arr['drivers_cout_by_agent'] = $drivers_cout_by_agent
    return $arr;
}

答案 1 :(得分:1)

你似乎有一个数组,只想添加一些元素,所以这可以做到。

$tmp= $request->user();
$tmp['driver_count'] = (where you get it from);
$tmp['count_by_id'] = (where you get it from);
return $tmp;

(抱歉没有细节,我在我的手机上。如果这是您需要的,我会稍后扩展/更正或删除,如果不是。想要快速得到这个。)

答案 2 :(得分:0)

根据Serializing Models & Collections。您可以通过以下方式将其序列化为json或数组:

return $request->user()->toJson();
// or
return $request->user()->toArray();

还有一节关于将数据附加到json:Appending Values To JSON。但在您的情况下,您可以将数据序列化为数组,附加您的值并将其封装到json。

$returnData = $request->user()->toArray();
$returnData['foo'] = 'bar';

return json_encode($returnData);