Php 用密码替换数组的元素
我需要创建一个价格数组。所以我有一组基本价格和一组促销价格,如果促销价格低于基本价格,我就把它放在新的价格组中。为此,我编写了以下代码:Php 用密码替换数组的元素,php,arrays,replace,associative,Php,Arrays,Replace,Associative,我需要创建一个价格数组。所以我有一组基本价格和一组促销价格,如果促销价格低于基本价格,我就把它放在新的价格组中。为此,我编写了以下代码: <?php $array_base_prices = array( array('id'=>1, 'price'=>10), array('id'=>2, 'price'=>2), array('id'=>3, 'price'=>30), arr
<?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>";
?>
它工作得很好,但是我认为嵌套的
foreach
中的if
条件有点混乱。我正在使用多维关联数组,非常大,有很多键。因此,我想知道是否有更好的替代方案来实现相同的结果。对于我来说,确实没有足够的上下文来确保这是您的一个选项,但是从您的小示例中,我将数组声明更改为:
$array_base_prices = array(
1 => array("price" => 10, "something_else" => null)
);
如果您需要存储的数据不仅仅是价格,还可以使用阵列:
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];
}
}
关键是要将id作为父数组的索引。然后,嵌套循环转向以下方向:
$array_base_prices = array(
1 => array("price" => 10, "something_else" => null)
);
谢谢你的回答。考虑到这些数组是通道数组,我认为按照您的建议修改结构更为实际,即将id作为父数组的键。为了更好地管理后续段落中需要的数量,我还将id设置为子数组元素:$array\u base\u prices=array(1=>array(“id”=>1,“price”=>10,“something\u else”=>null)等);