Sun Z Sun Z - 20 days ago 6
PHP Question

Loop through 2x two-dimensional arrays to compare

Good morning, for an stock inventory I want to update it automaticaly when we sell a car. I have 2x two-dimensional arrays:

$array_purchase = array(
array(
'Name' => 'Mecedes',
'Purchase' => 10
),
array(
'Name' => 'BMW',
'Purchase' => 20
),
array(
'Name' => 'FIAT',
'Purchase' => 30
)
);


$array_sales = array(
array(
'Name' => 'Mecedes',
'Purchase' => 5
),
array(
'Name' => 'BMW',
'Purchase' => 10
)
);


I tried to use this, but didn't work for me:

foreach($array_sales as $sName => $sSold){

if(isset($array_purchase[$sName])){
$array_purchase[$sName] - $sSold;
}

}


The results should something like


Mercedes: 5x (10-5)

Fiat: 30x (30 - 0)

BMW: 10x (20 - 10)


Any help will be appreciated.

Thanks in advance for your time.

Answer
foreach($array_purchase as $key => $value){
   if(isset($array_sales[$key]['Purchase'])){
      echo($array_purchase[$key]['Name']." ".($array_purchase[$key]['Purchase'] - $array_sales[$key]['Purchase']));
      echo("<br />");
   } else {
      echo($array_purchase[$key]['Name']." ".$array_purchase[$key]['Purchase']);
      echo("<br />");
   }
};

This code can offcourse be optimized a lot, but it will give you a good idea how you should loop through the data.