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;
我希望将1个元素推送到我的数据
答案 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;
}