arrays - 如何更新laravel中的主数组
问题描述
我需要帮助更新 Main Array 并在 foreach 循环中更改其数据。这是我的代码:
$query = DB::table('autostk')
->where('autostk.branchid', $branch_id)
->where('autostk.itemcode', $request->itemcode)
->whereDate('autostk.date', '<=', $request->tdate)
->where('autostk.branchid', $branch_id)
->leftjoin('journal', 'autostk.refno', '=', 'journal.vno')
->where('journal.code', '>=', 100)
->where('journal.branchid', $branch_id)
->leftjoin('accounts', 'journal.code', '=', 'accounts.code')
->where('accounts.branchid', $branch_id)
->select('journal.code', 'accounts.title', 'autostk.*')
->orderBY('date')->get()
->map(function ($item, $key) {
return (array)$item;
})
->all();
foreach ($query as $row) {
if (is_null($row['qtyin'])) {
$row['qtyin'] = 0;
}
if (is_null($row['qtyout'])) {
$row['qtyout'] = 0;
}
if (is_null($row['rate'])) {
$row['rate'] = 0;
}
if ($row['vtype'] = 'PI' && $row['qtyin'] > 0) {
$stkval = ($bal * $avgrate) + ($row['qtyin'] * $row['rate']);
if ($bal > 0) {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
if ($bal > 0 && $stkval > 0) {
$avgrate = $stkval / $bal;
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
$avgrate = $row['rate'];
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
}
$row['balqty'] = $bal;
$row['avgrate'] = $avgrate;
}
我的问题是如何使用对 $row 所做的更改来更新 $query。我是 php 和 laravel 的新手,尝试过 push()、put() 等。不知道在这种情况下需要哪个函数。
解决方案
选项1
//use toArray() in last to get the result as an array
$query = ...->all()->toArray();
foreach ($query as $key => $row) {
//inside here instead of using $row, use $query[$key]
//so for example $row['rate'] = 0; becomes:
$query[$key]['rate'] = 0;
}
选项 2
//use toArray() in last to get the result as an array
$query = ...->all()->toArray();
//use pass by reference with help of &
foreach ($query as $key => &$row) {
...
}
但是,使用引用传递方法时要非常小心,否则如果您重用相同的数组,您可能会遇到问题。
选项 3
$query = ...->all();
foreach ($query as $key => $row) {
//access it as object
//instead of using $row['qtyin'] use:
$row->qtyin = 0;
}
它的经销商的选择:)