【问题标题】:Converting array to JSON object array将数组转换为 JSON 对象数组
【发布时间】:2016-09-19 03:21:14
【问题描述】:

我在从以下代码获取 JSON 对象数组时遇到问题。

public function staffStatusFromSameDept($deptID)
{
    $sameDeptEmployee=StaffsModel::where("DepartmentID","=",$deptID)->get();
    $count=$sameDeptEmployee->count();
    if ($count>0) 
    {
        foreach ($sameDeptEmployee as  $value) 
        {
            $data=DB::table('status')
                 ->join('staffs','status.StaffPin', '=', 'staffs.StaffPin')
                 ->select('staffs.StaffName','staffs.DesignationName',
                          'status.staffStatus', 'status.currentLocation',
                          'staffs.EmailID','staffs.MobileNO','status.returnTime','staffs.Photo' )
                 ->where('staffs.StaffPin','=',$value->StaffPin)
                 ->get();

            $response[]=$data;
        }
    }
    else{
        $response=["error" => "Invalid Department ID"];
    }

    header('Content-type: application/json');
    echo json_encode($response);
}

实际输出:

[[{"StaffName":"Mamun hoten","DesignationName":"PO(MF)","staffStatus":"working","currentLocation":"rangpur","EmailID":"mamun@brac .net","MobileNO":"01716340278","re​​turnTime":"04:30","Photo":"helal.jpg"}],[{"StaffName":"nahid hasan","DesignationName":"PO(MF)","staffStatus":"working","currentLocation":"rangpur","EmailID":"nahid@brac.net","MobileNO":"01716340278", "returnTime":"04:30","照片":"helal.jpg"}]]

预期输出:

[{"StaffName":"Mamun hooken","DesignationName":"PO(MF)","staffStatus":"working","currentLocation":"rangpur","EmailID":"mamun@brac. net","MobileNO":"01716340278","re​​turnTime":"04:30","Photo":"helal.jpg"},{"StaffName":"nahid hasan","DesignationName":"PO(MF)","staffStatus":"working","currentLocation":"rangpur","EmailID":"nahid@brac.net","MobileNO":"01716340278", "returnTime":"04:30","照片":"helal.jpg"}]

我的代码中的问题是每个人都详细介绍了 JSON 对象数组。但是我想要一个 JSON 对象数组以及我将从这个 JSON 对象数组中获得的每个人的详细信息。

【问题讨论】:

    标签: json laravel foreach


    【解决方案1】:

    因为->get() 将返回找到的记录数组。

    因此,如果您的查询始终有 1 条记录,请将 ->get() 更改为 ->first(),否则使用 $response = array_merge($response, $data) 而不是 $response[] = $data

    【讨论】:

      【解决方案2】:

      您可以简单地将$response[]=$data; 更改为$response=$data;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-21
        • 2020-10-02
        • 1970-01-01
        • 2018-09-12
        • 2015-10-30
        • 1970-01-01
        相关资源
        最近更新 更多