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

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条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失