6

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.

3
  • And where is the problem? Where are you stuck with which code? Commented Jun 7, 2016 at 9:38
  • change this javascript to php function getObjectKeyIndex(obj, keyToFind) { var i = 0, key; for (key in obj) { if (key == keyToFind) { return i; } i++; } return null; } Commented Jun 7, 2016 at 9:39
  • What is the expected output? Commented Jun 11, 2016 at 6:37

7 Answers 7

8
+50

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

and yes as @Andrew said make sure you decrement the current player value to get the index right ;)
3

Try this code.

$info = json_decode('json string');
$currentPlayer = $info->currentPlayer;
$batsman = $info->scorecards[0]->batting->players[$currentPlayer];
echo "<div>{$batsman->name}</div>\n";

Also, note that arrays in PHP are zero-based. If currentPlayer index in json data is based on 1 (rare case, but it exists sometimes) you will ned to use

$batsman = $info->scorecards[0]->batting->players[$currentPlayer - 1];

to get right item from array.

1 Comment

FYI, ($currentPlayer - 1) not required for my case $currentPlayer works
3

If you just want to fix your foreach

  1. $read_json->scorecards->batting should become $read_json->scorecards[0]->batting

  2. if($val == 5) should become if($batsmen == 5)

  3. $name = $batsmen->name; should become $name = $val->name;

1 Comment

I see. But it still says below your question that the bounty is still open. You need to click on the bounty award icon next to your selected answer, as it says here
2

You need to use json_decode and array_keys for the array keys from the json.

$json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
$result = json_decode ($json, true);
$keys = array_keys($result);
print_r($keys); //Array ( [0] => key1 [1] => key2 [2] => key3 )

11 Comments

only count from first line till the end.
Your partial json is not valid.
json is only for reference. it is valid json
in other words how can i display only the 5th line
please, run your json here, and if works then let me do what you want?
|
2

In Php, You can use the code below, if you wan to fix it using foreach loop

foreach($json->entries as $row)

{

    foreach($row as $key => $val)
    {
        echo $key . ': ' . $val;
        echo '<br>';
    }

}

Comments

1

please have a look following code

$json=json_decode($data)->scorecards[0]->batting->players;
foreach ($json as $key => $value) {
  if($key==5){
    echo $value->name ;
  }
}

Comments

1

You can do it using converting JSON string to Array

$json_str = '{   
"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"}
            ]
        }
    }
]

}';

Decode your JSON string using "json_decode" and you get array

$json_decode_str = json_decode($json_str, true);

Now using foreach you can do anything

if($json_decode_str['scorecards']){

    foreach($json_decode_str['scorecards'] as $scorecard){

        $player_index = 1;
        if($scorecard['batting']['players']){

            foreach($scorecard['batting']['players'] as $player){

                if($player_index == 5){
                    echo $player['name'];
                }

                $player_index++;
            }

        }

    }

}

Maybe this one help you :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.