Click here to Skip to main content
15,888,070 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need solution for How to compare two key and value and find max key value from array.

explain:- I have below array in this if **url** and **con code** both are same than higher **amount** array should display and unmatch data should be display please provide sollution for same .

$array = array(
array(
"id" => 1,
"amount" => 10,
"url" => 'https://play.google.com/store/apps/details?id=com.my.heroesofutopia',
"con" => array('US' =>array('id'=> '1','code'=>'US')),
),
array(
"id" => 2,
"amount" => 3,
"url" => 'https://play.google.com/store/apps/details?id=com.my.heroesofutopia' ,
"con" => array('US' =>array('id'=> '1','code'=>'US')),
),
array(
"id" => 3,
"amount" => 19,
"url" => 'https://play.google.com/store/apps/details?id=com.my.heroesofutopia' ,
"con" => array('US' =>array('id'=> '1','code'=>'US'),'Uk' =>array('id'=> '2','code'=>'UK')),
),
array(
"id" => 4,
"amount" => 50,
"url" => 'https://play.google.com/store/apps/details?id=com.my.heroesofutopia1111' ,
"con" => array('US' =>array('id'=> '1','code'=>'US'),'Uk' =>array('id'=> '2','code'=>'UK')),
),
);

Please check result i want
in this example 1 and 2 id have same url and country code so from this two we have to choose higher amount one.so we choose this and id 3 and 4 are not match this criteria so its will remain same in this array because ID 3 has same url but has different country code and ID 4 has different url.

i want this result.please provide sollution for same,
thanks in advance...!!

array( "id" => 1,
"amount" => 10,
"url" => 'https://play.google.com/store/apps/details?id=com.my.heroesofutopia',
"con" => array('US' =>array('id'=> '1','code'=>'US')),
),
array(
"id" => 3,
"amount" => 19,
"url" => 'https://play.google.com/store/apps/details?id=com.my.heroesofutopia' ,
"con" => array('US' =>array('id'=> '1','code'=>'US'),'Uk' =>array('id'=> '2','code'=>'UK')),
),
array(
"id" => 4,
"amount" => 50,
"url" => 'https://play.google.com/store/apps/details?id=com.my.heroesofutopia1111' ,
"con" => array('US' =>array('id'=> '1','code'=>'US'),'Uk' =>array('id'=> '2','code'=>'UK')),
),

What I have tried:

My code is for that is



$output = [];
foreach($array as $data){

if(!isset($output[$data['url']]) ){

$output[$data['url']] = $data;

}
elseif( $output[$data['url']]['amount'] < $data['amount']){

$output[$data['url']] = $data;
}

}
echo "
"; print_r($output);
Posted
Updated 5-Apr-17 18:56pm

1 solution

$output = array_reduce($array, function ($carry, $itemA) {
return array_filter($carry, function ($itemB) use($itemA) {
return (
$itemB['url'] != $itemA['url']
|| $itemB['con'] != $itemA['con']
|| $itemB['amount'] >= $itemA['amount']
);
});
}, $array);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900