簡體   English   中英

如何合並兩個多維 arrays 並調整現有值?

[英]How to merge two multidimensional arrays and adjust existing values?

我想將以下 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
    )
);

如何結合這 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
    )
);

誰能幫我?

一種方法是找到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);

結果將是:

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
        )

)

使用array_push() ,它將給定值推送到數組。

array_push($pricesForAllCustomer,$customerSpecificPrices);

它會像這樣返回合並值,

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM