我想显示返回数据以转换json

时间:2017-03-01 06:04:44

标签: php json laravel-5

我的表数据库在sub_bidang模型中

id  id_bidang       name    
1      1            Backend Developer   
2      1            Frontend Developer  
3      2            Senior Marketing

我希望按字段id bidang

显示数组nama sub bidang中的所有名称
$data = Posting::find($id);

    foreach ($data->sub_bidang as $value) {

        $data = [

            'id posting job' => $data->id_posting_job,
            'id kategori' => $data->id_kategori,
            'nama kategori' => $data->kategori_posting['nama'],
            'id bidang' => $data->id_bidang,
            'nama bidang' => $data->bidang['nama'],
            'nama sub bidang' => [
                'bidang' => $value->nama
            ]  
        ]; 

        return response()->json($data);
    } 

但不起作用,只需在数组nama sub bidang中显示后端开发人员。像这样

{
  "id posting job": 1,
  "id kategori": 1,
  "nama kategori": "Part Time",
  "id bidang": 1,
  "nama bidang": "IT",
  "nama sub bidang": {
    "bidang": "Backend Developer"
  }
}

应该有显示后端开发人员和前端开发人员, 有什么问题?

1 个答案:

答案 0 :(得分:2)

这里尝试以下

.......................
.......................
$result_data = array();
foreach ($data->sub_bidang as $value) {

    $result_data[] = array(
        'id posting job' => $data->id_posting_job,
        'id kategori' => $data->id_kategori,
        'nama kategori' => $data->kategori_posting['nama'],
        'id bidang' => $data->id_bidang,
        'nama bidang' => $data->bidang['nama'],
        'nama sub bidang' => array(
            'bidang' => $value->nama
        )
    ); 


} 
return response()->json($result_data);

注意: $result_date是php数组,因此response()->json()方法会自动生成JSON