如何在内部数组中进行foreach

时间:2017-03-03 11:49:06

标签: php laravel

在我的关系数据库中,

如果id_sub_bidang = 1那么nama_sub_bidang"前端deveoper"。

如果id_sub_bidang = 2那么nama_sub_bidang"高级营销"

我的代码

$data = Company::find($id);

            $result_data = array();

            foreach ($data->posting_job as $hasil) {

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

                   $result_data[] = [

                        'id_sub_bidang' => $hasil->id_sub_bidang,
                        'nama_sub_bidang' => $value->nama
                    ]; 
                }

            }

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

输出

    [
      {
        "id_sub_bidang": 1,
        "nama_sub_bidang": "Frontend Developer"
      },
      {
        "id_sub_bidang": 1,
        "nama_sub_bidang": "Senior Marketing"
      },
      {
        "id_sub_bidang": 2,
        "nama_sub_bidang": "Frontend Developer"
      },
      {
        "id_sub_bidang": 2,
        "nama_sub_bidang": "Senior Marketing"
      }
]

预期结果

[
      {
        "id_sub_bidang": 1,
        "nama_sub_bidang": "Frontend Developer"
      },
      {
        "id_sub_bidang": 2,
        "nama_sub_bidang": "Senior Marketing"
      }
]

我想循环内部数组但不起作用。所以,我用这种方式。 有什么问题?

2 个答案:

答案 0 :(得分:0)

将您的foreach循环更改为:

foreach ($data->posting_job as $hasil) {

        foreach ( $hasil->id_sub_bidang as $hasilid) {

                $result_data[] = ['id_sub_bidang' => $hasil->id_sub_bidang];

                foreach ($data->sub_bidang as $value) {
                   $result_data[] = ['nama_sub_bidang' => $value->nama]; 
                }
        }
}

答案 1 :(得分:0)

构建一个数组,然后使用递归方法通过重复条目清理数组。

array_replace_recursive

另一种解决方案

    $empty_stats = Array(
    'id_sub_bidang' => null,
    'nama_sub_bidang' => null
);

foreach ($array as $value) {
    if (!array_key_exists($id_sub_bidang, $array)) {
        $array[] = $empty_stats;
    }
    $array[] = [

        'id_sub_bidang' => $hasil->id_sub_bidang,
        'nama_sub_bidang' => $value->nama
    ]; 
}