简体   繁体   English

如何使用php格式化此json数据

[英]how to format this json data using php

the link is here .please look at this bellow details and tell me how to get the value of each {} block 链接在这里。请查看下面的详细信息,并告诉我如何获取每个{}块的值

JSON DATA JSON数据

 {
        "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

<?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();
}
?>

I want to get the VALUE of the joson data.. 我想获取joson数据的值。

How to format above json data using php 如何使用PHP格式化上面的JSON数据

Use 采用

json_decode($jsonObject, true); json_decode($ jsonObject,true);

this function will convert your json data in to php array. 此功能会将您的json数据转换为php数组。 But the code you are writing seems to be very inefficient, you should not run your queries in foreach() variables, you should use like this. 但是您正在编写的代码似乎效率很低,您不应该在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();
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM