1

I have this small snippet of code in PHP to read a JSON sent by Ajax, and when I read it, the return is 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'];
}

Thank You.

cornelb
  • 6,046
  • 3
  • 19
  • 30
  • 2
    Try `var_dump($data);` and see what you get, notice the nesting of the arrays. – KIKO Software Mar 27 '22 at 19:36
  • If I use the json this way it works: $json='[{"Code":"1","Name":"Carlos"},{"Code":"2","Name":"Charles" },{"Code":"3", "Name":"Joseph"}]' The problem is that it is being sent like that by Ajax. – Valdir Sola Mar 27 '22 at 19:39
  • Required reading: [How to extract and access data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-to-extract-and-access-data-from-json-with-php) – ADyson Mar 27 '22 at 20:16

2 Answers2

3

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

foreach ($data['value'] as $row) {
    print_r($row);
    $code = $row['Code'];
    $name = $row['Name'];
}
cornelb
  • 6,046
  • 3
  • 19
  • 30
1

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

Elio Bteich
  • 123
  • 1
  • 10