Recently a question came up on Json, and this is just one technique to deal with it.
The in coming Json was:
{"document_tone":{"tones":[{"score":0.706991,"tone_id":"sadness","tone_name":"Sadness"},{"score":0.955445,"tone_id":"analytical","tone_name":"Analytical"}]}}
To make it easier to work with one could remove the beginning:
{"document_tone":{"tones":
And end
}}
Knowing those are the same each time.
So then to remove them, your variable $str would already hold the Json, here I am putting it in hard coded:
$prefix = '{"document_tone":{"tones":';
$str = '{"document_tone":{"tones":[{"score":0.706991,"tone_id":"sadness","tone_name":"Sadness"},{"score":0.955445,"tone_id":"analytical","tone_name":"Analytical"}]}}';
if (substr($str, 0, strlen($prefix)) == $prefix) {
$str = substr($str, strlen($prefix));
}
$substring = '}}';
if (substr($str, -strlen($substring)) === $substring) {
$str = substr($str, 0, strlen($str) - strlen($substring));
}
That would just leave
[{"score":0.706991,"tone_id":"sadness","tone_name":"Sadness"},{"score":0.955445,"tone_id":"analytical","tone_name":"Analytical"}]
To deal with
Then:
$json = json_decode($str, true);
A var dump looks like:
array(2) {
[0]=>
array(3) {
["score"]=>
float(0.706991)
["tone_id"]=>
string(7) "sadness"
["tone_name"]=>
string(7) "Sadness"
}
[1]=>
array(3) {
["score"]=>
float(0.955445)
["tone_id"]=>
string(10) "analytical"
["tone_name"]=>
string(10) "Analytical"
}
}
To loop over:
$keys = array_keys($json);
for ($i = 0; $i < count($json); $i++) {
echo $keys[$i] > 0 ? " -------------------- <br>" : '';
foreach ($json[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
}
}
Which gives
score : 0.706991
tone_id : sadness
tone_name : Sadness
--------------------
score : 0.955445
tone_id : analytical
tone_name : Analytical
I just put in
echo $keys[$i] > 0 ? " -------------------- <br>" : '';
to have a separator.
I did all in controller here just for demo, but a real app, pass the final result to the view
and loop over.
To note, as array's get more nested, it can be a trick and some trial and error to loop correctly.
If you do a search on looping a php array, nested, associative, etc, there are tons of stackoverflow questions.
If it was easy, there would not be so many questions.
Just remember some trial and error is required at times.
And if you had this in a variable called $str:
{"score":0.706991,"tone_id":"sadness","tone_name":"Sadness"},{"score":0.955445,"tone_id":"analytical","tone_name":"Analytical"}
Notice no brackets.
You could:
$str = chr(91) . $str . chr(93);
Just prior to using json_decode.
I'd welcome @cronix or @snapey or anyone to add a more complex example, as hopefully this guide will help someone.