-1

I am trying to pull certain parts of information I have in a JSON file but unable to get the parts I want. At the moment I am focusing on getting barcode and can then work out how to do it from there.

I have tried several different ways to trying to select the part of the array I want but cannot work out why it errors with Undefined index: barcode every time

<?php
$host="localhost";
$username="root";
$password="root";
$dbname="demo";
//create a Connection
$conn=mysqli_connect($host,$username,$password,$dbname);

//check the connection

if(!$conn)
{
 die("connection does not established successfully :".mysqli_connect_error());
}
//read the json file using php method   file_get_contents('filename.json')
$jsondata=file_get_contents('file.json');

//convert json into php array
$data=json_decode($jsondata,true);

//get the details of student from JSON file and store it in the variable one by one.
$id=$data['data']['barcode'];

print_r($id)
?>

I expect it to show the barcode section from my JSON file.

{
    "data": [
        {
            "baseSku": "71JNDAZA",
            "sku": "71JNDAZA08",
            "additionalSku": [],
            "barcode": "889042766774",
            "additionalBarcode": [],
            "model": "71JND",
            "title": "Arta Lace Ruffle Dress"
        }
    ]
}

But at this moment I seem unable to select anything from in here.

ThisIsLegend1016
  • 105
  • 1
  • 4
  • 13
  • 5
    You can see from the JSON that `data` is an array, therefore you need to access it through its array index, in this case 0: `$data['data'][0]['barcode']`. – Chris White Apr 29 '19 at 14:24
  • 1
    `$data['data']` is an array of arrays. There just happens to be only one top-level element in it. `var_dump($data)` and you'll see it. – Patrick Q Apr 29 '19 at 14:24
  • 2
    Possible duplicate of ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Patrick Q Apr 29 '19 at 14:24
  • 1
    Two more links: [mcve] and [ask]. – Ulrich Eckhardt Apr 29 '19 at 15:04

1 Answers1

1

As Chris White mention (just making it formal answer) the data section is an array so the right way to access it is:

echo $data["data"][0]["barcode"];
dWinder
  • 11,597
  • 3
  • 24
  • 39