StudioTime
StudioTime

Reputation: 23959

Parse JSON Response PHP

I have the following JSON data which I'm trying to parse the categories:

{
"skimlinksProductAPI": {
    "status": 200,
    "message": "OK",
    "version": 3,
    "categories": {
        "1": "Animals",
        "2": "Animals > Live Animals",
        "3": "Animals > Pet Supplies",
        "4": "Animals > Pet Supplies > Bird Supplies",
        "5": "Animals > Pet Supplies > Bird Supplies > Bird Cages & Stands",
        "6": "Animals > Pet Supplies > Bird Supplies > Bird Food",
        "7": "Animals > Pet Supplies > Bird Supplies > Bird Ladders & Perches",
        "8": "Animals > Pet Supplies > Bird Supplies > Bird Toys",
        ...
    }
  }
}

I'm trying the following but not working:

$catList = json_decode(file_get_contents('http://api-product.skimlinks.com/categories?key=MY_KEY&format=json'),true);

$catList=$catList['skimlinksProductAPI']['categories'];

foreach ($catList as $element){

    echo $element[0].' - '.$element[1];

}

Upvotes: 0

Views: 1251

Answers (1)

Barmar
Barmar

Reputation: 780724

The elements of categories aren't sub-arrays, they're just key-value pairs. The foreach should be:

foreach ($catList as $id => $element){
     echo $id . ' - ' . $element;
}

Upvotes: 1

Related Questions