Notice: Undefined offset: error with JSON and PHP

Links for php scripts

Moderators: egami, macek, gesf

Post Reply
annierizzini
New php-forum User
New php-forum User
Posts: 1
Joined: Wed Jun 27, 2018 4:42 pm

Wed Jun 27, 2018 4:48 pm

Hello world!

I'm starting with JSON, and I have a form list as follows:
"sentence_id": 1,
"text": "I hate #ThisPhoneCompany products, you'd have to torture me to get me to use #ThisPhone.",
"tones": [
{ "score": 0.591225, "tone_id": "anger", "tone_name": "Anger" },
{ "score": 0.560098, "tone_id": "analytical", "tone_name": "Analytical" },
{ "score": 0.645985, "tone_id": "confident", "tone_name": "Confident" }
] },
{ "sentence_id": 2,
"text": "The emojis in #ThisPhone are stupid.",
"tones": [
{ "score": 0.760538, "tone_id": "anger", "tone_name": "Anger" }
] },

My code to go through the list is:
$jsonObj = json_decode($result, true);
foreach($jsonObj["sentences_tone"] as $value){
for($i = 0; $i < count($value['tones'][$i]['score']); $i++){
print_r ($value);
echo '<br/><br/>valor: '.$value['tones'][$i]['score'][$i];
echo '<br/>sentimento: '.$value['tones'][$i]['tone_name'].'<br/>'; };
echo '<br/>texto: '.$value['text']; };

The problem is that whenever there is more than one "tones" (como o "sentence_id": 1, where I have three "tones"), the error appears Notice: Undefined offset: 1 in /Applications/XAMPP/xamppfiles/htdocs/toneAnalyzer/test.php on line 28, but with "sentence_id": 2, where there is only one, shows correct, without an error...Any idea?
Attachments
Captura de Tela 2018-06-27 às 17.35.25.png
Captura de Tela 2018-06-27 às 17.35.25.png (65.14 KiB) Viewed 77 times
Captura de Tela 2018-06-27 às 17.35.11.png
Captura de Tela 2018-06-27 às 17.35.11.png (125.78 KiB) Viewed 77 times

Post Reply