phparrays

Array Match & Add Values to First array


I have two arrays one with conversion_offer_id, conversions & payout. Now i want to match it with another array and add all the values of first array to second array and if not then add values of conversion & payout as 0.

Array 1 ($conversions)

[
{
"conversion_offer_id": 90,
"conversions": 15,
"payout": 225
},
{
"conversion_offer_id": 196,
"conversions": 1,
"payout": 120
},
{
"conversion_offer_id": 720,
"conversions": 53,
"payout": 1590
}
] 

Array 2 ($clkcs)

[
{
"clicks": 142,
"offer_currency": 45,
"click_offer_id": 90,
"click_affiliate_id": 9106,
"offer_name": "BKS",
"offer_id": 90,
"currency_symbol": "₹"
},
{
"clicks": 8,
"offer_currency": 45,
"click_offer_id": 196,
"click_affiliate_id": 9106,
"offer_name": "FFU",
"offer_id": 196,
"currency_symbol": "₹"
},
{
"clicks": 1,
"offer_currency": 45,
"click_offer_id": 246,
"click_affiliate_id": 9106,
"offer_name": "GFT",
"offer_id": 246,
"currency_symbol": "₹"
},
{
"clicks": 1,
"offer_currency": 45,
"click_offer_id": 334,
"click_affiliate_id": 9106,
"offer_name": "JPR",
"offer_id": 334,
"currency_symbol": "₹"
},
{
"clicks": 1,
"offer_currency": 45,
"click_offer_id": 622,
"click_affiliate_id": 9106,
"offer_name": "TWS",
"offer_id": 622,
"currency_symbol": "₹"
},
{
"clicks": 1197,
"offer_currency": 45,
"click_offer_id": 720,
"click_affiliate_id": 9106,
"offer_name": "KPS",
"offer_id": 720,
"currency_symbol": "₹"
}
]

My Logic to achieve

foreach($clkcs as $k=>$key){
            foreach($conversions as $ckey){
                if($key['click_offer_id']==$ckey['conversion_offer_id']){

                    $clkcs[$k]['offer_id']=$ckey['conversion_offer_id'];

                    $clkcs[$k]['conversions']=$ckey['conversions'];
                    $clkcs[$k]['payout']=$ckey['payout'];

                }else{
                    $clkcs[$k]['conversions']='0';
                    $clkcs[$k]['payout']='0';

                }
            }

        }

Conversions & payout for only last matching values are populating fine. For rest of them its 0.

But it should also add the conversion & payout for offer ID 90 & 196.

What i am doing wrong?


Solution

  • You need stop second foreach after success filling of $clkcs

    foreach($clkcs as $k=>$key){
        $clkcs[$k]['conversions']='0';
        $clkcs[$k]['payout']='0';
    
        foreach($conversions as $ckey){
            if($key['click_offer_id']==$ckey['conversion_offer_id']){
                $clkcs[$k]['offer_id']=$ckey['conversion_offer_id'];
    
                $clkcs[$k]['conversions']=$ckey['conversions'];
                $clkcs[$k]['payout']=$ckey['payout'];
    
                break;
            }
        }
    }