0

I have a JSON data.

When I write echo $response;

My scree is:

results: 1,
paging: {
current: 1,
total: 1
},
response: [
{
predictions: {
winner: {
id: 217,
name: "SC Braga",
comment: "Win or draw"
},
win_or_draw: true,
under_over: null,
goals: {
home: "-2.5",
away: "-2.5"
},
advice: "Double chance : SC Braga or draw",
percent: {
home: "45%",
draw: "45%",
away: "10%"
}
},
...etc

I need predictions segment inside response.

I try to echo $response['response']['predictions']['winner']->name

Also I try to

$response['response'] = $a and foreach($a as $k){ echo $k;}

But all of them does not work.

How can solve this problem?

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74

1 Answers1

1

If the problem is with accessing json properties in PHP, then you need to convert the json data into a PHP array first. The conversion is done using the json_decode function. For example:

$php_array = json_decode( $json_object, true );

The true argument tells json_decode to convert to a PHP associative array which allows you to use this syntax:

$php_array['response']['predictions']['winner']['name']

See the PHP docs for details.

kofeigen
  • 1,331
  • 4
  • 8
  • @kefeigen my response is here :$response = curl_exec($curl); if I try $php_array = json_decode( $response, true ); echo $$php_array['response']['predictions']['winner']['name']; is empty – Deniz Demirel Mar 19 '23 at 21:05
  • @DenizDemirel `$response` might not be in valid JSON format. You can check to see if the call to `json_decode` was successful by using [json_last_error_msg](https://www.php.net/manual/en/function.json-last-error-msg.php). You can also echo the converted response using `print_r( $php_array )` to validate its format. – kofeigen Mar 19 '23 at 21:17