如何在php中解码以下url

时间:2017-05-10 16:04:49

标签: php json

我尝试解码以下网址,但我无法获得结果。

{"main_cat":[{"main_cat_id":"1","main_cat_name":"Door"},{"main_cat_id":"2","main_cat_name":"Sunmica"}]}

我试过下面的代码,请告诉我我在哪里做错了......

<?php
    include("connect.php");
    $response['main_cat'] = array();
    $json = file_get_contents("http://localhost//Project/Fashion/select_main_cat.php");
    $dat["main_cat"] = json_decode($json);
    foreach ($dat["main_cat"] as $key->$val ) {
        ?>
    <td><?php
        echo $dat["main_cat"]->$key;

    ?></td>
    <?php
}
?>

错误:

Error desc

2 个答案:

答案 0 :(得分:0)

解码

{"main_cat": [{"main_cat_id": "1", "main_cat_name": "Door"}, {"main_cat_id": "2", "main_cat_name": "Sunmica"}]}

会给你一个这样的对象

$dat = {
  main_cat:
    [
        {
           main_cat_id: 1
           main_cat_name: Door
        },
        {
           main_cat_id: 2
           main_cat_name: Sunmica
        }
    ]
}

所以你可以像这样迭代:

$dat = json_decode($json);
foreach ($dat["main_cat"] as $key => $val ): ?>
    <td>
        <?php echo $val->main_cat_name; ?>
    </td>
<?php endforeach;?>

答案 1 :(得分:0)

您收到的JSON字符串的结构如下:

"main_cat":
    |
    |--("main_cat_id: 1", "main_cat_name: Door")
    |
    |--("main_cat_id: 2", "main_cat_name: Sunmica") 

所以在这个JSON的顶部你会找到"main_cat"对象,它包含另外两个对象的数组。

解析所有键及其相对值的代码可以是这样的:

$dat["main_cat"] = json_decode($json);
foreach ($dat["main_cat"]->main_cat as $cat ) {
    foreach ($cat as $key => $val) {
        ?><td><?php echo $key . ': ' . $val ?></td><?php
    }
}