PHP在foreach中更改数组值 [英] PHP changing array value in foreach

查看:209
本文介绍了PHP在foreach中更改数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对php很陌生,因为我过去2个小时一直在寻找信息,所以似乎没有帮助的例子。
我有什么我称为嵌套数组?他们两个人。我几乎需要能够匹配来自不同数组的ID。并从库存中扣除金额。

im quite new to php and as i was looking for info for last 2 hours, no examples seemed to help. i have what i think is called nested array? two of them. pretty much i need to be able to match id from different arrays. and detract the amount from stock.

<?php
$items = array(
array('id' => 34, 'name' => 'Kompiuterius ASUS ASX89', 'price' => 639.00, 'stock' => 3),
array('id' => 1008, 'name' => 'Monitorius AOC 27IPS', 'price' => 223.00, 'stock' => 7),
array('id' => 965, 'name' => 'Tracer kilimėlis pelytei', 'price' => 2.00, 'stock' => 20),
array('id' => 567, 'name' => 'Pelytė Logitech A52', 'price' => 16.00, 'stock' => 14),
array('id' => 1123, 'name' => 'Klaviatūra Razer Chroma 2016', 'price' => 109.00, 'stock' => 6)
);
$orders = array(
array('purchase_date' => '2016-11-12', 'item_id' => 34, 'quantity' => 1),
array('purchase_date' => '2016-11-12', 'item_id' => 1008, 'quantity' => 2),
array('purchase_date' => '2016-11-13', 'item_id' => 965, 'quantity' => 1),
array('purchase_date' => '2016-11-15', 'item_id' => 1123, 'quantity' => 4),
array('purchase_date' => '2016-11-11', 'item_id' => 34, 'quantity' => 2)
);

foreach ($orders as $order){
  $purchase_id = $order['item_id'];
  $purchase_quantity = $order['quantity'];
  foreach ($items as $item){
    $stock_id = $item['id'];
    $stock_quantity = $item['stock'];
    if ($purchase_id == $stock_id){
      $stock_quantity = $stock_quantity - $purchase_quantity;
      $item['stock'] = $stock_quantity; //something with &?
      echo 'Prekiu, pazymetu numeriu ' . $stock_id . ' liko: ' . $stock_quantity . ' vnt. ' . '<br/>';
    }
  }
}
?>

这就是我的代码。我认为这可能行得通,因为在退出 if功能之前,我会在下一行中给股票赋予新的价值。但我想我错了

thats pretty much my code. i thought this might work, as with following line i would give new value to stock before exiting "if" function. but i guess im wrong

$item['stock'] = $stock_quantity;

欢迎任何建议

EDIT1 :我想做的是将$ items数组中的id与$ orders中的id进行比较。如果它与库存减去数量匹配,则显示剩余库存。希望它更清晰

what im trying to do is compare id from $items array with id from $orders. if it matches from stock subtract quantity and display the remaining stock. hope its more clear

推荐答案

foreach循环通过将每个值复制到一个临时变量中来工作。

A foreach loop works by copying each value into a temporary variable.

如果要编辑原始数组,则有两种解决方案:

If you want to edit the original array, you have two solutions :

可以使用& :

foreach ($items as &$item) {
    /*...*/
    $item['stock'] = $stock_quantity;
}

或者使用 $ key => $ value 表示法,然后编辑原始数组:

Or use the $key=>$value notation and edit the original array :

foreach ($items as $key => $item) {
    /*...*/
    $items[$key]['stock'] = $stock_quantity;
}

这篇关于PHP在foreach中更改数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆