简体   繁体   English

替换性地替换数组的元素

[英]substitute the elements of an array coditionally

I need to create an array of prices. 我需要创建一系列价格。 So I've an array of base prices and an array of promotional prices, if the promotional price is lower than the base price, I put it in the new array of prices. 因此,我有一系列基本价格和一系列促销价格,如果促销价格低于基本价格,则将其放入新的价格系列中。 For this purpose I wrote this code: 为此,我编写了以下代码:

<?php 
    $array_base_prices = array(
        array('id'=>1, 'price'=>10),
        array('id'=>2, 'price'=>2),
        array('id'=>3, 'price'=>30),
        array('id'=>4, 'price'=>40)
     );

     $array_promo = array(
        array('id'=>1, 'price'=>20),
        array('id'=>2, 'price'=>5),
        array('id'=>3, 'price'=>2)
     );

     $base_prices_with_promo = array();

     foreach ( $array_base_prices as $j => $u ) {

        foreach ( $array_promo as $k => $v ) {

           if ( ($v['id'] == $u['id']) && $u['price'] < $v['price']) {

                $base_prices_with_promo[$j]['id'] = $array_base_prices[$j]['id'];
                $base_prices_with_promo[$j]['price'] = $array_base_prices[$j]['price'];

           }

           if ( ($v['id'] == $u['id']) && $u['price'] > $v['price']) {

                $base_prices_with_promo[$j]['id'] = $array_promo[$k]['id'];
                $base_prices_with_promo[$j]['price'] = $array_promo[$k]['price'];            

           }

        }

    }

    $base_prices_with_promo = array_replace( $array_base_prices, $base_prices_with_promo );

    echo "<pre>";
    print_r($base_prices_with_promo);
    echo "</pre>";

?>

and it works fine, but I think that the if conditions into the nested foreach are a little messy. 而且效果很好,但是我认为嵌套到foreach中的if条件有点混乱。 I'm working with multidimensional, associative arrays, very big with a lot of keys. 我正在使用多维,关联数组,其中包含很多键,因此非常庞大。 So I'm wondering if there is any better alternative to achieve the same result. 所以我想知道是否有更好的选择来达到相同的结果。

There's really not enough context for me to be sure that this is an option for you, but from your little example I would change the array declaration to this: 对于我来说,确实没有足够的上下文来确保这是您的选择,但是从您的小示例中,我将数组声明更改为:

$array_base_prices = array(
    1 => 10,
    2 => 2,
    3 => 30,
    4 => 40
);

$array_promo = array(
    1 => 20,
    2 => 5,
    3 => 2
);

Or use an array if you need to store more data than just price: 或者,如果您需要存储的数据不仅限于价格,还可以使用数组:

$array_base_prices = array(
    1 => array("price" => 10, "something_else" => null)
);

The point is to have the id as index of the parent array. 关键是将id作为父数组的索引。 Then your nested loops turn to this: 然后,您的嵌套循环将变为:

foreach ($array_base_prices as $id => $base_price) {
    $base_prices_with_promo[$id] = $base_price;
    if (isset($array_promo[$id]) && $base_price > $array_promo[$id]) {
        $base_prices_with_promo[$id] = $array_promo[$id];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM