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. 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. 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];
}
}