0

I'm trying to print a value of my array but i keep having the same error "Warning: Illegal string offset".

I don't know why i keep having this error, it is a json array and it is supposed to be right ..

thank you in advance


    $bson = MongoDB\BSON\fromPHP($entry);
    $json= MongoDB\BSON\toJSON($bson);
    var_dump($js);

    echo $js['nom'];
string(1115) ""{ '_id' : { '$oid' : '5ca51d1b7d42c4ccb4d67618' }, 'nom' : 'Led Zeppelin', 'type' : 'G', 'pays' : 'Angleterre', 'genre' : 'Heavy Metal', 'albums' : [ { 'nom_album' : 'Led Zeppelin', 'annee' : '1969', 'prix' : '16.50', 'image' : '' }, { 'nom_album' : 'Led Zeppelin II', 'annee' : '1969', 'prix' : '16.50', 'image' : '' }, { 'nom_album' : 'Led Zeppelin III', 'annee' : '1970', 'prix' : '16.50', 'image' : '' }, { 'nom_album' : 'Led Zeppelin IV', 'annee' : '1971', 'prix' : '16.50', 'image' : '' }, { 'nom_album' : 'Houses Of The Holy', 'annee' : '1973', 'prix' : '13.20', 'image' : '' }, { 'nom_album' : 'Physical Graffiti', 'annee' : '1975', 'prix' : '16.50', 'image' : '' }, { 'nom_album' : 'Presence', 'annee' : '1976', 'prix' : '18.81', 'image' : '' }, { 'nom_album' : 'In Through The Outdoor', 'annee' : '1979', 'prix' : '18.70', 'image' : '' }, { 'nom_album' : 'Coda', 'annee' : '1982', 'prix' : '16.50', 'image' : '' }, { 'nom_album' : 'The Song Reamins The Same', 'annee' : '1976', 'prix' : '19.80', 'image' : '' }, { 'nom_album' : 'Live BBC Sessions', 'annee' : '1997', 'prix' : '19.86', 'image' : '' } ] }"" 
Warning: Illegal string offset 'nom' in C:\xampp\htdocs\music\index.php on line 23

i want to have : nom, nom_album in the same row

I already looked for other posts and i don't find my answer, i'm stuck on that

  • Don't break your JSON text, and don't try to use values without checking them first. – miken32 Apr 03 '19 at 22:45
  • 1
    Also you might want to look into `json_decode`, not `json_encode`. But that still won't work if you're messing with your quotes. – miken32 Apr 03 '19 at 22:47
  • Your JSON is definitely invalid--it has single quotes instead of double quotes. That's invalid JSON. Otherwise, @Mohammed Yassine CHABLI's answer is correct. – Zenexer Apr 03 '19 at 22:50

1 Answers1

2

The $js is not array , that why you have the Warning

You have to decode json to array first:

$res = json_decode($js, true);
echo $res['nom']; 
Zenexer
  • 18,788
  • 9
  • 71
  • 77
Yassine CHABLI
  • 3,459
  • 2
  • 23
  • 43
  • ``` $bson = MongoDB\BSON\fromPHP($entry); $json= MongoDB\BSON\toJSON($bson); $js = json_encode($json); $res= json_decode($js, true); echo $res['nom']; ``` i get : Warning: Illegal string offset 'nom' in – Oktay Seeven Apr 03 '19 at 22:49
  • 1
    can you check the type of $js ? , **echo gettype($js);** – Yassine CHABLI Apr 03 '19 at 22:51