Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting undefined index when retrieving json value of key name having a dot within in PHP

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading