bma pachuau bma pachuau - 4 months ago 11
PHP Question

Multiply two arrays values based on the values on the other values

From the following array I am trying to multiple the quantity and the price on the condition that itemType is Zo.

(
[customer] => 4
[itemNo] => Array
(
[0] => 1
[1] => 2
)

[itemName] => Array
(
[0] => Type A
[1] => Type B
)

[itemType] => Array
(
[0] => Zo
[1] => Ram
)

[quantity] => Array
(
[0] => 2
[1] => 3
)

[price] => Array
(
[0] => 500
[1] => 2000
)
)


Here is what I have tried so far but with no success.

$lq = 0;
$total =0;

for ($i=0;$i<count($_REQUEST['price']);$i++) {
if(in_array("Ram", $_REQUEST['itemType'])){
$total += $_REQUEST['price'][$i] * $_REQUEST['quantity'][$i];
}else{
$lq += $_REQUEST['quantity'][$i];
}
}

echo ($total).'<br>';
echo ($lq);


My expected output is:

$total = 1000;//Quantity x Price
$lq = 3//Quantity only

Answer

You're not checking itemType of the same item that you're adding to the total. You're just checking whether any of the items have that itemType. You're also looking for Ram, not Zo.

if ($_REQUEST['itemType'][$i] == 'Zo') {
    $total += $_REQUEST['price'][$i] * $_REQUEST['quantity'][$i];
} else {
    $lq += $_REQUEST['quantity'][$i];
}