-1

I have the following json string collected from a file

{"v":1,"current":{"email_messages_count":0,"pipeline_id":1,"9bf19d1d179d05c17a14023d3022565264c4eb08":"83170420728","red":"83170420728","534":"83170420728","c4bde3465a51ba798737a02f34bd2db867493c2f":"83170420728"}}

I am trying to extract the value from key "9bf19d1d179d05c17a14023d3022565264c4eb08"

Whenever I try to do anything with this element it causes my program to crash. The difference I can see is that the key value starts with a number then characters. If the key value starts with a character then followed by numbers it will work?

Here is the code:

$result = file_get_contents("testfile.txt",true);
$dataIN = json_decode($result, true);
$current = json_encode($dataIN[current], true);

$testData2 = $dataIN[current][c4bde3465a51ba798737a02f34bd2db867493c2f];
echo $testData2;

If I was to run the above code it would work, however if I add:

$testData3 = $dataIN[current][9bf19d1d179d05c17a14023d3022565264c4eb08];
echo $testData3;

The program will crash and I get no output

Any help greatly appreciated, thank you in advance

IMO
  • 307
  • 1
  • 3
  • 12
  • Try to put the key in single quotes during access i.e., `$dataIN['current']['c4bde3465a51ba798737a02f34bd2db867493c2f...']` I'm not sure why it crashes instead of giving an error message. Give it a try – Beshambher Chaukhwan Jun 11 '21 at 10:32
  • 2
    Does this answer your question? [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – AymDev Jun 11 '21 at 10:44
  • My previous comment was automatic, your question is a duplicate, you can find your answer here exactly: https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/12773272#12773272 – AymDev Jun 11 '21 at 10:45

1 Answers1

1

In PHP, you always have to include strings in single or double quotes.

This is what you should write:

$result = file_get_contents("testfile.txt", true);
$dataIN = json_decode($result, true);
$current = json_encode($dataIN["current"], true);

$testData2 = $dataIN[current]["9bf19d1d179d05c17a14023d3022565264c4eb08"];

The script works with

$testData2 = $dataIN[current][bf19d1d179d05c17a14023d3022565264c4eb08];

and not with

$testData2 = $dataIN[current][9bf19d1d179d05c17a14023d3022565264c4eb08];

because PHP automatically assumes that anything that's not enclosed into quotes that starts with a letter is a string literal. But the string

9bf19d1d179d05c17a14023d3022565264c4eb08

starts with a number, so PHP cannot make that assumption, and this causes the error.

mrodo
  • 565
  • 5
  • 21