Kamalpreet Singh
Kamalpreet Singh

Reputation: 143

Combine Array with Json in PhP

I am having an API that is getting data's in Json format.

[
   {
       "id": "bitcoin",
       "name": "Bitcoin",
       "symbol": "BTC",
       "rank": "1",
       "price_usd": "7365.07",
       "price_btc": "1.0",
       "24h_volume_usd": "4900640000.0",
       "market_cap_usd": "124873929597",
       "available_supply": "16954887.0",
       "total_supply": "16954887.0",
       "max_supply": "21000000.0",
       "percent_change_1h": "0.55",
       "percent_change_24h": "5.92",
       "percent_change_7d": "-7.93",
       "last_updated": "1522733968",
       "price_eur": "5987.30108524",
       "24h_volume_eur": "3983887076.48",
       "market_cap_eur": "101514013335"
     },
     {
       "id": "ethereum",
       "name": "Ethereum",
       "symbol": "ETH",
       "rank": "2",
       "price_usd": "397.12",
       "price_btc": "0.0541563",
       "24h_volume_usd": "1216740000.0",
       "market_cap_usd": "39149486407.0",
       "available_supply": "98583517.0",
       "total_supply": "98583517.0",
       "max_supply": null,
       "percent_change_1h": "0.07",
       "percent_change_24h": "3.51",
       "percent_change_7d": "-15.33",
       "last_updated": "1522733953",
       "price_eur": "322.83155584",
       "24h_volume_eur": "989126881.68",
       "market_cap_eur": "31825870284.0"
     }
]

On the other hand, I am having Object array

Array

( [0] => stdClass Object ( [id] => 42 [user_id] => 39 [coin_rank] => 2 )

[1] => stdClass Object
    (
        [id] => 3
        [user_id] => 39
        [coin_rank] => 6
    )

[2] => stdClass Object
    (
        [id] => 8
        [user_id] => 39
        [coin_rank] => 8
    )

)



I want only Json array that match coin rank array key coin_rank from array index value.

like get only ethereum array if rank and coin rank matched. else neglected


Sorry if you didn't get my point, Ask me without hesitation.

Regards

Upvotes: 0

Views: 30

Answers (1)

Bhaskar Jain
Bhaskar Jain

Reputation: 1691

Run a loop and find rank key in json array.

       $jsonArr = json_decode($json, true);
       $new = array();
       foreach($arr as $v){
           $key = array_search($v->coin_rank, array_column($jsonArr, 'rank'));
           if($key !== false){
               $new[] =  $jsonArr[$key];
           }
       }
       print_r($new);

Demo

Upvotes: 1

Related Questions