php会话数组如果相同的ID添加一个元素
Posted
技术标签:
【中文标题】php会话数组如果相同的ID添加一个元素【英文标题】:php session array add an element if same ID 【发布时间】:2017-01-06 09:41:10 【问题描述】:我得到了下面的会话数组来存储购物车物品:
print_r($_SESSION['items']):
Array
(
[0] => Array
(
[p_name] => Product A
[p_price] => 13.90
[p_seller] => 2001
)
[1] => Array
(
[p_name] => Product B
[p_price] => 2.00
[p_seller] => 2002
)
[2] => Array
(
[p_name] => Product C
[p_price] => 1.20
[p_seller] => 2002
)
[3] => Array
(
[p_name] => Product D
[p_price] => 50.00
[p_seller] => 2001
)
)
我有一个循环从数据库中调用附加数据:
while($res = $shipment->fetch_object())
$seller_id = $res->seller;
$shipment_cost = $res->shipment_fee;
//array_push($_SESSION['items']['p_fee'], $shipment_cost);
让我们说,在一个循环中我得到以下数据:
$seller_id = 2001; $shipment_cost = 5.00
$seller_id = 2002; $shipment_cost = 3.00
我想分配并添加一个名为 ['p_fee']
的额外元素到其各自的组 ['p_seller']
如果 $seller_id(2001) == ['p_seller'] ---> array_push($_SESSION['items']['p_fee'], '5.00')
如果 $seller_id(2002) == ['p_seller'] ---> array_push($_SESSION['items']['p_fee'], '3.00')
这样可以吗?
$_SESSION['items']
最终可能包含以下元素:
Array
(
[0] => Array
(
[p_name] => Product A
[p_price] => 13.90
[p_seller] => 2001
[p_fee] => 5.00
)
[1] => Array
(
[p_name] => Product B
[p_price] => 2.00
[p_seller] => 2002
[p_fee] => 3.00
)
[2] => Array
(
[p_name] => Product C
[p_price] => 1.20
[p_seller] => 2002
[p_fee] => 3.00
)
[3] => Array
(
[p_name] => Product D
[p_price] => 50.00
[p_seller] => 2001
[p_fee] => 5.00
)
)
【问题讨论】:
对我来说修改两个查询似乎是合乎逻辑的,我假设您正在运行以从一个查询生成此数据。那你就不用这么折腾了 【参考方案1】:是的,你可以。
您可以通过添加值来实现此目的,同时从数据库中检索它。例如:
while($res = $shipment->fetch_object())
$seller_id = $res->seller;
$shipment_cost = $res->shipment_fee;
foreach ($_SESSION['items'] as $key => $item)
if ($item['p_seller'] === $seller_id)
$_SESSION['items'][$key]['p_fee'] = $shipment_cost;
更好(更快)的方法是在sellerId和costs之间建立一个映射,然后放到session中:
$costMapping = array();
while($res = $shipment->fetch_object())
$seller_id = $res->seller;
$shipment_cost = $res->shipment_fee;
$costMapping[$seller_id] = $shipment_cost;
foreach ($_SESSION['items'] as $key => $item)
if (isset($costMapping[$item['p_seller']]))
$_SESSION['items'][$key]['p_fee'] = $costMapping[$item['p_seller']];
这样你只有 2 个循环,不管你有多少卖家。
【讨论】:
【参考方案2】:是的,有可能,你应该做两个循环,第一个是收取费用,第二个是把它们与物品关联起来。
// Fill the fees first
$fees = [];
while($res = $shipment->fetch_object())
$seller_id = $res->seller;
$shipment_cost = $res->shipment_fee;
$fees[$seller_id] = $shipment_fee;
// Assign fees
foreach ($_SESSION['items'] as &$item)
$fee = $fees[$item['p_seller']] ?: 0; // <- fee will be 0 if not found !
$item['p_fee'] = $fee;
希望这会有所帮助:)
【讨论】:
以上是关于php会话数组如果相同的ID添加一个元素的主要内容,如果未能解决你的问题,请参考以下文章