【问题标题】:How to merge two multidimensional arrays and adjust existing values?如何合并两个多维数组并调整现有值?
【发布时间】:2019-11-02 09:08:55
【问题描述】:

我想将以下数组放在一起并计算最优惠的价格。

$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 个数组组合起来以达到以下结果?

$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
    )
);

谁能帮帮我?

【问题讨论】:

  • 到目前为止,您自己有没有尝试过?
  • 你的意思是合并而不是合并。 Read this

标签: php arrays merge


【解决方案1】:

一种方法是找到from 值大于pricesForAllCustomer to 值的元素并将其放在这些元素之间(假设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
        )

)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 2020-04-21
    • 2023-03-28
    • 2015-12-27
    • 2011-11-26
    • 1970-01-01
    相关资源
    最近更新 更多