I have 2 multidimensional Arrays with Flightdates (Price, Date, Airline,..). I want to merge and remove duplicates that have the same date but I need to keep the cheaper one . I have always the same flight, but different prices.
$array1 = array(
[0] => Array
(
[price] => 191
[date1] => 22-07-2016
[date2] => 30-07-2016
[airline] => Lufthansa
)
[1] => Array
(
[price] => 80
[date1] => 25-07-2016
[date2] => 30-07-2016
[airline] => Easyjet
)
[2] => Array
(
[price] => 243
[date1] => 10-08-2016
[date2] => 36-08-2016
[airline] => Airberlin
)
);
$array2 = array(
[0] => Array
(
[price] => 230
[date1] => 22-07-2016
[date2] => 30-07-2016
[airline] => Lufthansa
)
[1] => Array
(
[price] => 80
[date1] => 25-07-2016
[date2] => 30-07-2016
[airline] => Easyjet
)
[2] => Array
(
[price] => 200
[date1] => 10-08-2016
[date2] => 36-08-2016
[airline] => Airberlin
)
);
Just loop through the first array and match the price in second array with respect to key of first array and push the values into into new array..
First Answer
<?php
$newArray = array();
foreach($array1 as $key =>$val)
{
if($val['price'] <= $array2[$key]['price'])
{
$newArray[] = $val;
}
else
{
$newArray[] = $array2[$key];
}
}
print_r($newArray);
?>
LIVE EXAMPLE: CLICK HERE
Second Answer
$newArray = array();
foreach($array1 as $key => $val)
{
foreach($array2 as $k => $v)
{
if($val['date1'] == $v['date1'] && $val['date2'] == $v['date2'] && $val['airline'] == $v['airline'])
{
if($val['price'] <= $array2[$key]['price'])
{
$newArray[] = $val;
}
else
{
$newArray[] = $v;
}
}
}
}
print_r($newArray);
LIVE EXAMPLE: CLICK HERE
This will give you:
Array
(
[0] => Array
(
[price] => 191
[date1] => 22-07-2016
[date2] => 30-07-2016
[airline] => Lufthansa
)
[1] => Array
(
[price] => 80
[date1] => 22-07-2016
[date2] => 30-07-2016
[airline] => Easyjet
)
[2] => Array
(
[price] => 200
[date1] => 22-07-2016
[date2] => 30-07-2016
[airline] => Airberlin
)
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.