推元素阵列laravel

时间:2018-05-28 06:14:50

标签: php arrays laravel

sory帮我添加元素到数组

这段代码我的控制器

$datas = PengembalianAset::select('kd_brg', 'nm_brg', 'nm_lgkp_brg', 'keterangan', 'ruang_id', 'no_ikn')
        ->find($request->id)->toArray();

foreach ($datas as $safety) {
            $dataSet[] = [
                'new element' => 1,
                $safety,
            ];
        }
        print_r($dataSet); exit;

array output

enter image description here

我希望将1个元素推送到我的数据

which I expected

enter image description here

但结果是这样的 But the result is like this, not what I expected

enter image description here

3 个答案:

答案 0 :(得分:1)

尝试以下方法:

$datas = PengembalianAset::select('kd_brg', 'nm_brg', 'nm_lgkp_brg', 'keterangan', 'ruang_id', 'no_ikn')->find($request->id)->toArray();

foreach ($datas as $safety) {
  $safety['new_element'] = 1;
  $dataSet[] =   $safety;
}
print_r($dataSet); exit;

或者您也可以将其添加到现有数组

$datas = PengembalianAset::select('kd_brg', 'nm_brg', 'nm_lgkp_brg', 'keterangan', 'ruang_id', 'no_ikn')->find($request->id)->toArray();

foreach ($datas as &$safety) { //Passing by Reference
  $safety['new element'] = 1
}
print_r($datas); exit;

答案 1 :(得分:1)

你也可以这样做 -

$datas = PengembalianAset::select('kd_brg', 'nm_brg', 'nm_lgkp_brg', 
         'keterangan', 'ruang_id', 'no_ikn', '1 AS `new element`')
         ->find($request->id)->toArray();

仅从查询中获取1 new element。因为它具有相同的价值。不需要额外的循环。

答案 2 :(得分:0)

改变你的foreach

foreach ($datas as $safety) {
            $dataSet[] = [
                'new element' => 1,
                $safety,
            ];
        }

foreach ($datas as $safety) {
            $safety['new element'] = 1;
            $dataSet[] = $safety;
        }