NulisDefo NulisDefo - 8 days ago 5
PHP Question

PHP changing array value in 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

Answer

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;
}