dongshimao7115 2016-12-01 14:59
浏览 92
已采纳

PHP在foreach中更改数组值

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/>';
    }
  }
}
?>

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;

any suggestions would be welcome

EDIT1: 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

  • 写回答

3条回答 默认 最新

  • dougupang0901 2016-12-01 15:05
    关注

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

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

    Either pass the value with a reference, using & :

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

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

    foreach ($items as $key => $item) {
        /*...*/
        $items[$key]['stock'] = $stock_quantity;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!