Armageddon80 Armageddon80 - 4 months ago 9
PHP Question

Get a value from JSON array in PHP

I have a JSON array returned by an API. I need to get the "value" and "value_high" part from the JSON under the Mann Co Supply Crate Key.

I have made a script that gets the values of the ['response']['success'] but I can't get any other values.

{
"response": {
"success": 1,
"current_time": 1401869275,
"raw_usd_value": 0.245,
"usd_currency": "metal",
"usd_currency_index": 5002,
"items": {
"Mann Co. Supply Crate Key": {
"defindex": [
5021
],
"prices": {
"6": {
"Tradable": {
"Craftable": [
{
"item_name": "Mann Co. Supply Crate Key",
"quality": 6,
"craftable": "Craftable",
"tradable": "Tradable",
"priceindex": 0,
"defindex": [
5021
],
"value": 8.22,
"currency": "metal",
"value_high": 8.33,
"last_update": 1401486984,
"difference": 0.22
}
]
}
}
}
},

Answer

first you need to format your json properly (remove unneccessary comma, add missing }):

{
        "response": {
            "success": 1,
            "current_time": 1401869275,
            "raw_usd_value": 0.245,
            "usd_currency": "metal",
            "usd_currency_index": 5002,
            "items": {
                "Mann Co. Supply Crate Key": {
                    "defindex": [
                        5021
                    ],
                    "prices": {
                        "6": {
                            "Tradable": {
                                "Craftable": [
                                    {
                                        "item_name": "Mann Co. Supply Crate Key",
                                        "quality": 6,
                                        "craftable": "Craftable",
                                        "tradable": "Tradable",
                                        "priceindex": 0,
                                        "defindex": [
                                            5021
                                        ],
                                        "value": 8.22,
                                        "currency": "metal",
                                        "value_high": 8.33,
                                        "last_update": 1401486984,
                                        "difference": 0.22
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        }
    }

then use json_decode() and access the data by iterating down to the values needed (your json should be saved to the variable $json):

$decoded = json_decode($json);

$value = $decoded->response->items->{'Mann Co. Supply Crate Key'}->prices->{'6'}->Tradable->Craftable[0]->value;
$value_high = $decoded->response->items->{'Mann Co. Supply Crate Key'}->prices->{'6'}->Tradable->Craftable[0]->value_high;