MitchCool1 MitchCool1 - 6 months ago 20
PHP Question

PHP - Getting array element from Json

I'm working with the JSON here: http://steamcommunity.com/id/mitch8910/inventory/json/730/2/

I'm trying to get the

tags[{"name":""}]
part of it. For example, I would want the 'container', from '"name":"Container"'

This is my code here:

$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');
$json = json_decode($data);

foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->tags[1];
}


tags[]
is an array, though I did
tags[1]
, I don't awlays want the '1'th element because the position of "name" could change in the array for different elements, I just did this to test, but I got an error. I have tried multiple ways with multiple errors, that why I'm not posting all the error code.

Answer

The simplest way may be to do an extra loop to grab all the name elements:

$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');

$json = json_decode($data);

foreach ($json->rgDescriptions as $mydata)
{
    foreach($mydata->tags as $tag) {
        echo $tag->name;
    }
}

or to get the first name of each tag group:

foreach ($json->rgDescriptions as $mydata)
{
    echo $mydata->tags[0]->name;
}