如何从关联数组中获取数据

时间:2017-03-06 17:50:57

标签: php arrays json

如何编写PHP以从中获取数据。

{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}

我试过这个

$BookingDetail["room"]["single_room"];

但得到了这样的结果

  

非法字符串偏移'房间'

  

非法字符串偏移'single_room'

如何解决。

2 个答案:

答案 0 :(得分:0)

试试这个...你需要解码json,你得到一个PHP对象,然后你就可以访问每个元素..

<?php

$str = '{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}';

$json = json_decode($str);

echo "<pre>";
print_r($json);
echo "</pre>";

echo $json->room->single_room;

顺便说一句,我觉得你的json是无效的。您可以在http://jsonlint.com/

查看此信息

答案 1 :(得分:0)

您使用的字符串看起来像JSON,但它不会检出有效。请参阅JSONLint.com ...编辑它以使其有效(单行)...

{"room": [{"single_room": 1, "twin_room": 3}], "total_amount": [{"amount": 20899}], "travelernum": [{"total": 1 }]}

或(多线)......

{
    "room": [{
        "single_room": 1,
        "twin_room": 3
    }],
    "total_amount": [{
        "amount": 20899
    }],
    "travelernum": [{
        "total": 1
    }]
}

如果这是您的所有字符串所在的格式,您可以先使用...将它们操作为有效的JSON ...

$original_string = '{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}';
$new_string = str_replace("}{", ",", $original_string);  // replace }{ with ,

一旦你的字符串是有效的JSON格式,转换为PHP数组,因为相当简单,使用这样的东西......

$BookingDetail = json_decode($new_string, true);  //true param gets assoc array

我测试了上面的所有代码并且它工作正常。有关将JSON字符串转换为PHP数组的更多详细信息,请参阅PHP json_decode()函数参考。
http://php.net/manual/en/function.json-decode.php