将数组转换为 JSON 对象数组

问题描述 投票:0回答:2

我在从以下代码获取 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 hosen","DesignationName":"PO(MF)","staffStatus":"working","currentLocation":"rangpur","EmailID":"[电子邮件受保护] ","MobileNO":"01716340278","returnTime":"04:30","Photo":"helal.jpg"}],[{"StaffName":"nahid hasan","DesignationName":"PO(MF)","staffStatus":"工作","currentLocation":"rangpur","EmailID":"[电子邮件受保护]","MobileNO":"01716340278" ,"返回时间":"04:30","照片":"helal.jpg"}]]

预期输出:

[{"StaffName":"Mamun hosen","DesignationName":"PO(MF)","staffStatus":"working","currentLocation":"rangpur","EmailID":"[电子邮件受保护] ","MobileNO":"01716340278","returnTime":"04:30","照片":"helal.jpg"},{"StaffName":"nahid hasan","DesignationName":"PO(MF)","staffStatus":"工作","currentLocation":"rangpur","EmailID":"[电子邮件受保护]","MobileNO":"01716340278" ,"返回时间":"04:30","照片":"helal.jpg"}]

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

php json laravel foreach
2个回答
0
投票

因为

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

因此,如果您的查询始终有 1 条记录,请将

->get()
更改为
->first()
,否则使用
$response  = array_merge($response, $data)
而不是
$response[] = $data


0
投票

您只需将

$response[]=$data;
更改为
$response=$data;

© www.soinside.com 2019 - 2024. All rights reserved.