0

I have a JSON similar to the following:

{
    "name": "Activities",
    "description": "Activities",
    "parent_group_id": 0,
    "display": "Activities",
    "group_id": 7,
    "stamps": [
        {
            "stamp_id": 14,
            "name": "Stamp 14",
            "rank": 2
        },
        {
            "stamp_id": 20,
            "name": "Stamp 20",
            "rank": 4
        }
    ]
},
{
    "name": "Games",
    "description": "Games",
    "parent_group_id": 0,
    "display": "Games",
    "group_id": 6,
    "stamps": [
        {
            "stamp_id": 33,
            "name": "Stamp 33",
            "rank": 3
        },
        {
            "stamp_id": 31,
            "name": "Stamp 31",
            "rank": 1
        }
    ]
}

I want to get a list of each of the stamp_ids seperated by commas through PHP (eg. 14,20,33,31)

I have already tried this, with no luck:

$stampsdata     = json_decode($stampsjson, true);
$numberofstamps = $stampsdata['stamps']['stamp_id']);

Can anyone help?

1
  • It seems like your json is invalid. A json object may only have one root, but here it has multiple json root elements. Validate your json here Commented Nov 22, 2015 at 17:58

1 Answer 1

3

decode the JSON with json_decode and use array_column to get the IDs.

working solution:

// true needed to transform object to associative array
// $json contains your JSON string

$data = json_decode($json, true);

$stamps = [];
foreach ($data as $obj) {
    $stamps[] = array_column($obj['stamps'], 'stamp_id');
}

// implode sub arrays and concatenate string
$str = '';

foreach ($stamps as $stamp) {
    $sub = implode(',', $stamp);
    $str .= $sub . ',';
}

// remove trailing comma
$stampIds = rtrim($str, ',');
print ($stampIds);
Sign up to request clarification or add additional context in comments.

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.