我有一个 MySQL 查询:
SELECT id, order_no, reference, description, total_cost FROM bookorders
while 循环中的结果正在构建一个数组:
if (!array_key_exists($order_no, $orders)) {
$orders[$order_no] = array(array(
'reference' => $reference,
'description' => $description,
'total_cost' => $total_cost,
'discount' => 0,
'total_cost_withdiscount' => $total_cost
));
} else {
$orders[$order_no][] = array(
'reference' => $reference,
'description' => $description,
'total_cost' => $total_cost,
'discount' => 0,
'total_cost_withdiscount' => $total_cost
);
}
这就是它的样子:
Array
(
[12345] => Array
(
[0] => Array
(
[reference] => abc
[description] => Book Product 1
[total_cost] => 8.99
[discount] => 0
[total_cost_withdiscount] => 8.99
)
)
[67890] => Array
(
[0] => Array
(
[reference] => abc
[description] => Book Product 1
[total_cost] => 8.99
[discount] => 0
[total_cost_withdiscount] => 8.99
)
[1] => Array
(
[reference] => def
[description] => Book Product 2
[total_cost] => 24.99
[discount] => 0
[total_cost_withdiscount] => 24.99
)
)
)
在同一个表中还有折扣行,因此对于订单 67890,有 8 折扣供引用 def。
在运行查询结果时(这会将折扣作为单独的行显示),如何找出该引用是否已存在并更新“discount”和“total_cost_withdiscount”值?
因此,对于上面的示例,我想更改此:
[67890] => Array
(
[0] => Array
(
[reference] => abc
[description] => Book Product 1
[total_cost] => 8.99
[discount] => 0
[total_cost_withdiscount] => 8.99
)
[1] => Array
(
[reference] => def
[description] => Book Product 2
[total_cost] => 24.99
[discount] => 0
[total_cost_withdiscount] => 24.99
)
)
对此:
[67890] => Array
(
[0] => Array
(
[reference] => abc
[description] => Book Product 1
[total_cost] => 8.99
[discount] => 0
[total_cost_withdiscount] => 8.99
)
[1] => Array
(
[reference] => def
[description] => Book Product 2
[total_cost] => 24.99
[discount] => 8.00
[total_cost_withdiscount] => 16.99
)
)
当我在 mysql 查询的 while 循环内构建整个数组时,我需要更新这些值。我已经尝试过,但没有成功:
if ($orders[$order_no]["reference"] == $reference)
编辑
折扣是同一表中的另一行,因此折扣金额将显示为 $total_cost。
所以对于上面的内容,它是:
$id, $order_no, $reference, $description, $total_cost
1, 12345, abc, Book Product 1, 8.99
2, 67890, abc, Book Product 1, 8.99
3, 67890, def, Book Product 2, 24.99
4, 67890, def, discount, 8.00
最佳答案
$reference_to_find = 'def';
$order_no_to_find = 12345;
foreach ($orders as $order_no => $infos)
{
if ($order_no == $order_no_to_find)
{
foreach ($infos as $index => $item)
{
if ($item['reference'] == $reference_to_find)
{
// change
// $item['discount'] = ....
// set
$orders[$order_no][$index] = $item;
}
}
}
}
关于php - 在 PHP 中构建多维数组时更新其内的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21042716/