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?
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
)
)
Use array_push()
, it will push the given value to an array.
array_push($pricesForAllCustomer,$customerSpecificPrices);
it will return merged value like this,
Array ( [0] => Array ( [from] => 600 [to] => any [price] => 0.15 ) [1] => Array ( [0] => Array ( [from] => 1 [to] => 1799 [price] => 0.17 ) [1] => Array ( [from] => 1800 [to] => any [price] => 0.14 ) ) )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.