-1

My JSON file has this structure:

[
  {
    "n.name": "name1",
    "n.section": ["section1"]
  },
  {
    "n.name": "name2",
    "n.section": ["section2a", "section2b"]
  },

I parse it and having no error:

$input = file_get_contents(__DIR__ . "/node.json");
$jsonclean = removeBOM($input);
$data = json_decode($jsonclean, true);
echo 'Error code: '. $error; //Error code: 0

I want to echo only the values of the n.name keys (e.g. name1 name2 name3...). However using echo $data['n.name']; yields:

Notice: Undefined index: n.name

According to "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP, this is just a way for PHP to be more secure, and my method should work in theory. I then try:

$value = isset($_POST['n.name']) ? $_POST['n.name'] : '';
$value = !empty($_POST['n.name']) ? $_POST['n.name'] : '';
echo $value;

But it prints nothing. I'm not sure if that's the correct way to debug this?

Ooker
  • 1,969
  • 4
  • 28
  • 58

1 Answers1

2

Your json is a array of items, so when you decode it with json_decode, you should iterate over each item and retrieve the key that you want. Example:

$json = '[
  {
    "n.name": "name1",
    "n.section": ["section1"]
  },
  {
    "n.name": "name2",
    "n.section": ["section2a", "section2b"]
  }]';

  $data = json_decode($json, true);

  foreach($data as $item) {
      echo $item['n.name'] . "<br>";
  }

Output:

name1
name2
Silvio Ney
  • 46
  • 2
  • ah I see. At first I try `$data['n.name']`. What is the difference between `foreach($data as $item)` and `foreach ($data as $key => $val)`? – Ooker Jan 13 '22 at 11:24
  • You access them like `$data[0]['n.name']`. – Gregor Jan 13 '22 at 14:23
  • You should use some loop logic to iterate over your array or use $data[0]['n.name'], $data [1]['n.name'] etc but is not a good idea. You need to study about arrays at least. – Silvio Ney Jan 13 '22 at 14:31