-1

I'm having an issue reading my JSON file using PHP. I've tried a couple of things, but it seems I am unable to actually read the data. What would be the best way of achieving such thing? I have included a sample of my JSON data below:

{
    "UNIQUE ID":{
        "data":"123",
        "more_data":"456"
    },
    "UNIQUE ID":{
        "data":"789",
        "more_data":"123"
    }
}

My current PHP file looks like:

<?php

    $json = file_get_contents("./data/example.json");
    $data = json_decode($json, true);

    foreach($data as $single) {
        echo $single['UNIQUE ID'][0]['data'];
    }

?>

I receive no errors, it just does not show any data. A var_dump($data) does show it loads the JSON correctly.

Kevin
  • 874
  • 3
  • 16
  • 34
  • 3
    `$single['UNIQUE ID']['data'];` – sk11z00 Feb 09 '18 at 12:11
  • 3
    Use `var_dump($data);`, so that you see what the data structure you are dealing with here _actually_ is ... no idea where you imagine the additional [0] coming from. – CBroe Feb 09 '18 at 12:11
  • This JSON won't work well since both objects inside are referenced by same key, so the second one will override the first one. In effect you end up with an array containing only one element. – Mike Doe Feb 09 '18 at 12:13
  • @Mike I should have explained, but `UNIQUE ID` is being replaced with an actual unique id :) – Kevin Feb 09 '18 at 12:13
  • 1
    Maybe `var_dump($single);` inside the loop could have helped. Use `$single['data']`. – Marco Feb 09 '18 at 12:14
  • Increase your error reporting level. This will be raising a PHP notice, which would have helped you find the issue – iainn Feb 09 '18 at 12:15
  • 1
    @sk11z00 that won't work inside the loop, because `$single` is already `$data['UNIQUE ID']`, so you can't access `'UNIQUE ID'` key again. – Marco Feb 09 '18 at 12:18
  • @BusyBeaver yep, the iterance is on unique_id, with `$single['data'];` – sk11z00 Feb 09 '18 at 12:29

2 Answers2

2

Iterating over such hash array is quite easy:

$json = file_get_contents('./data/example.json');
$data = json_decode($json, true);

foreach ($data as $uniqueId => $array) {
    $data = $array['data'];
    $more_data = $array['more_data'];

    // go bananas here
}
Mike Doe
  • 16,349
  • 11
  • 65
  • 88
1

You're trying to access your data as if you were not iterating over your array with foreach.

Working example: https://3v4l.org/FZikX

<?php
foreach($data as $uniqueID => $single) {
    echo $single['data'];
}
Patito
  • 326
  • 3
  • 11