I would like to put together the following arrays and calculate best prices.
$pricesForAllCustomer = array( array( 'from' => '600', 'to' => 'any', 'price' => 0.15 ) );
$customerSpecificPrices = array ( array( 'from' => '1', 'to' => '1799', 'price' => 0.17 ), array( 'from' => '1800', 'to' => 'any', 'price' => 0.14 ) );
How can I combine these 2 arrays to achieve the following result?
$calculatedBestOffers = array( array( 'from' => '1', 'to' => '599', 'price' => 0.17 ), array( 'from' => '600', 'to' => '1799', 'price' => 0.15 ), array( 'from' => '1800', 'to' => 'any', 'price' => 0.14 ) );
Can anyone help me?
Advertisement
Answer
One way to do it is to find the element whose from
value is greater than pricesForAllCustomer
to
value and place it between these elements (assuming that customerSpecificPrices
is already ordered.):
$pricesForAllCustomer = array( array( 'from' => '600', 'to' => 'any', 'price' => 0.15 ) ); $customerSpecificPrices = array ( array( 'from' => '1', 'to' => '1799', 'price' => 0.17 ), array( 'from' => '1800', 'to' => 'any', 'price' => 0.14 ) ); $calculatedBestOffers = []; $foundPos = false; foreach($customerSpecificPrices as $key => $elem){ if(!$foundPos && $pricesForAllCustomer[0]['from'] < $elem['from']){ $calculatedBestOffers[$key-1]['to'] = $pricesForAllCustomer[0]['from']-1; $pricesForAllCustomer[0]['to'] = $elem['from']-1; $calculatedBestOffers[] = $pricesForAllCustomer[0]; $calculatedBestOffers[] = $elem; $foundPos = true; } else $calculatedBestOffers[] = $elem; } print_r($calculatedBestOffers);
The result will be:
Array ( [0] => Array ( [from] => 1 [to] => 599 [price] => 0.17 ) [1] => Array ( [from] => 600 [to] => 1799 [price] => 0.15 ) [2] => Array ( [from] => 1800 [to] => any [price] => 0.14 ) )