Search code examples
phparraysjsonjsondecoder

get specifc value from json with php


i need to get specific value only from a key, example:

i need to get value of the "odd": "6.25" from

"name": "Team To Score Last"->"value": "No goal" 

and the ODD

this is my json

"response": [
    {
    "league": {},
    "fixture": {},
    "update": "2020-05-15T09:49:32+00:00",
    "bookmakers": [
        {
        "id": 6,
        "name": "Bwin",
        "bets": [
            {}, {}, {}, {}, {}, {}, {},
            {}, {}, {}, {},
            {    
                "id": 15,
                "name": "Team To Score Last",
                "values": [
                        {
                            "value": "No goal",
                            "odd": "6.25"
                        }

i tried with

$odds =json_decode($responseodds, true);
$value=$odds['response'][0]['bookmakers'][0]['bets'][0]['name'];

unfortunately i get only value Team To Score Last


Solution

  • Loop over the bets array, and look for the bet name you are interested in.

    foreach ( $odds['response'][0]['bookmakers'][0]['bets'] as $bet){
        if ( $bet['name'] == "Team To Score Last") {
            // this is the one
            echo 'The odds were ' . $bet['values'][0]['odd'];
        }
    }
    

    If you want these odds for all of the bookies

    foreach ( $odds['response'][0]['bookmakers'] as $bookie){
    
        foreach ( $bookie as $bet){
            if ( $bet['name'] == "Team To Score Last") {
                // this is the one
                echo 'The bookie ' . $bookie['name'] . 'has the odds ' . $bet['values'][0]['odd'];
            }
        }
    }