[英]How to merge two multidimensional arrays and adjust existing values?
I would like to put together the following arrays and calculate best prices.我想将以下 arrays 放在一起并计算出最优惠的价格。
$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?如何结合这 2 个 arrays 来实现以下结果?
$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.):一种方法是找到
from
值大于pricesForAllCustomer
的元素to
value 并将其放在这些元素之间(假设customerSpecificPrices
已经订购。):
$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()
,它将给定值推送到数组。
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 ) ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.