请帮助我将元素添加到数组
此代码是我的控制器
$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 个元素推送到我的数据中
但是结果是这样的 但是结果是这样的,不是我想象的那样
你也可以这样做 -
$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
。因为它将具有相同的值。不需要额外的循环。
尝试以下操作:
$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;
更改你的 foreach
foreach ($datas as $safety) {
$dataSet[] = [
'new element' => 1,
$safety,
];
}
到
foreach ($datas as $safety) {
$safety['new element'] = 1;
$dataSet[] = $safety;
}
要使用 Laravel 集合方法向每行添加关联元素,您可以将
prepend()
添加到每行的前面,将 put()
添加到每行的后面。 PHPize 演示
var_export(
DB::table('PengembalianAset')
->get()
->map(fn($item) => collect($item)->prepend(1, 'new element'))
->toArray()
);
输出:
array (
0 =>
array (
'new element' => 1,
'kd_brg' => 101,
'nm_brg' => 'nama barang',
'nm_lgkp_brg' => 'nama lengkap barang',
'keterangan' => 'pisau cukur',
'ruang_id' => 1001,
'no_ikn' => 1001,
),
1 =>
array (
'new element' => 1,
'kd_brg' => 102,
'nm_brg' => 'nama barang2',
'nm_lgkp_brg' => 'nama lengkap barang 2',
'keterangan' => 'pisau jenggot',
'ruang_id' => 1002,
'no_ikn' => 1002,
),
)
如果您想使用
*
(不在 SELECT 子句中指定每一列)并使用纯数据库查询方法,那么您需要在结果集的末尾附加硬编码列。 PHPize 演示
var_export(
$db::table('PengembalianAset')
->selectRaw('*, 1 ' . $db::getQueryGrammar()->wrap('new element'))
->get()
->toArray()
);