如何使用php格式化这个json数据

时间:2013-03-31 05:25:25

标签: php json

链接为here。请查看此详细信息并告诉我如何获取每个{}块的值

JSON DATA

 {
        "id": "1",
        "0": "1",
        "value": "Addalachchenai",
        "1": "Addalachchenai",
        "department_id": "6",
        "2": "6",
        "ordering": "1",
        "3": "1"
    }

    {
        "id": "2",
        "0": "2",
        "value": "Akkaraipattu ",
        "1": "Akkaraipattu ",
        "department_id": "6",
        "2": "6",
        "ordering": "2",
        "3": "2"
    }

    {
        "id": "3",
        "0": "3",
        "value": "Ampara ",
        "1": "Ampara ",
        "department_id": "6",
        "2": "6",
        "ordering": "3",
        "3": "3"
    }

PHP

<?php

try {
    $dbh = new PDO('mysql:host=localhost;dbname=$db', $user, $pass);
    foreach($dbh->query('SELECT * FROM `jos_jea_towns` LIMIT 0, 500 ') as $row) {
       echo '<pre>' . json_encode($row, JSON_PRETTY_PRINT).'</pre>';

    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

我想得到joson数据的值..

如何使用php格式化上面的json数据

1 个答案:

答案 0 :(得分:2)

使用

  

json_decode($ jsonObject,true);

此函数会将您的json数据转换为php数组。但是你编写的代码似乎非常低效,你不应该在foreach()变量中运行你的查询,你应该这样使用。

<?php

try {
    $dbh = new PDO('mysql:host=localhost;dbname=$db', $user, $pass);
    $result = $dbh->query('SELECT * FROM `jos_jea_towns` LIMIT 0, 500 ');
    foreach($result as $row) {
       echo '<pre>';
       print_r($row);
       echo '</pre>';
       //echo '<pre>' . json_encode($row, JSON_PRETTY_PRINT).'</pre>';

    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>