无法在php上打印数组或子数组

时间:2019-04-03 22:39:39

标签: php arrays json mongodb bson

我正在尝试打印数组的值,但是我仍然遇到相同的错误 “警告:字符串偏移量非法”。

我不知道为什么我一直出现此错误,它是一个json数组,应该是正确的..

先谢谢您


    $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

我想拥有: nom,nom_album在同一行

我已经在寻找其他帖子了,但找不到答案,我坚持下去了

1 个答案:

答案 0 :(得分:1)

$ js 不是数组,这就是为什么要使用警告

您必须先解码json才能数组:

$res = json_decode($js, true);
echo $res['nom'];