Valdir Sola
Valdir Sola

Reputation: 41

I can't read JSON in PHP

I have this small snippet of code in PHP to read a JSON sent by AJAX, and when I read it, the results are always empty.

<?php
    
$json = '
{ "count": 3
, "value":
  [ { "Code": "1"
    , "Name": "Carlos"
    }
  , { "Code": "2"
    , "Name": "Charles" 
    }
  , { "Code": "3"
    , "Name": "Joseph"
    }
  ]
}';

$data = json_decode($json, true);

foreach($data as $row) {
    $code = $row['Code'];    
    $name = $row['Name'];
}

Upvotes: 1

Views: 59

Answers (2)

cornelb
cornelb

Reputation: 6066

You were close. $data['value'] has the list of items.

foreach ($data['value'] as $row) {
    print_r($row);
    $code = $row['Code'];
    $name = $row['Name'];
}

Upvotes: 3

Elio Bteich
Elio Bteich

Reputation: 152

try foreach($data["value"] as $row) instead of foreach($data as $row)

Upvotes: 1

Related Questions