Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get index of json key using php

Tags:

json

php

I want to find index of key from json array similar to this question Get index of a key in json but i need the solution using php.

here is my json (partial data)

{   
"currentOver":{
    "events":[]
},  
"matchString":"",
"currentPlayer":5, 
"previousOvers":[], 
"innings":[],   
"scorecards":[
    {
        "batting":{
            "players":[
                        {"id":16447,"name":"Rahul Roy"},
                        {"id":12633,"name":"Sijal Thomas"},
                        {"id":16446,"name":"Mohammed Reza"},
                        {"id":16509,"name":"Asif Khan"},
                        {"id":12633,"name":"Koyel Dijesh"},
                        {"id":16468,"name":"Shahrook"},
                        {"id":64691,"name":"Shafiq"},
                        {"id":6518,"name":"Ubaidulah"}
            ]
        }
    }
]

}

and php

foreach ($read_json->scorecards->batting->players as $batsmen => $val) {    
                if($val == 5) {   // if batsman index is 5 then display his name
                    $name = $batsmen->name;

                    echo "<div>$name</div>\n"; 

                }               
}

Please help me to solve this issue.Thanks in advance.

like image 880
Dil Dilshan Avatar asked Nov 30 '22 16:11

Dil Dilshan


1 Answers

I think this would suffice your requirement

http://codepad.org/XQDCKAsB

Find the code sample below as well.

       $json  = '{"currentOver":{"events": []},"matchString":"","currentPlayer":5,"previousOvers":[],"innings":[],"scorecards":[{"batting":{"players":[{"id":16447,"name":"Rahul Roy"},{"id":12633,"name":"Sijal Thomas"},{"id":16446,"name":"Mohammed Reza"},{"id":16509,"name":"Asif Khan"},{"id":12633,"name":"Koyel Dijesh"},{"id":16468,"name":"Shahrook"},{"id":64691,"name":"Shafiq"},{"id":6518,"name":"Ubaidulah"}]}}]}';

       $arr = json_decode($json);

       echo '<pre>';

       $currentPlayer = $arr->currentPlayer;

       echo $arr->scorecards[0]->batting->players[$currentPlayer-1]->name; 
like image 135
BlackBurn027 Avatar answered Dec 04 '22 05:12

BlackBurn027