douxing6532 2017-02-28 10:20
浏览 155
已采纳

如何使用PHP或JS将JSON转换为Value-Key Pair?

I want to Convert the JSON file to key:value pair, means

    [
     {"value":"apple","label":"apple"},
     {"value":"Google","label":"Google"}
    ]

Like below key:value pair format, like this

{
"apple": "apple",
"google": "google",
    .......
    .....
    ......
    ......
 }

So any one can tell me how can i do so, below is the Php file code, in which i have taken the data from the psql database and storing it in a file .

dbconn.php

<?php
$db = pg_connect("host=localhost port=5432 dbname=postgres       user=postgres password=root123");
 pg_select($db, 'post_log', $_POST); //selecting database


   $query=pg_query("SELECT name FROM account");
 $json=array();

    while($student=pg_fetch_array($query)){
         $json[]=array(
                    'value'=> $student["name"],
                    'label'=>$student["name"]);
    }


$textval = json_encode($json);  //encoding
file_put_contents('textvalues.txt', $textval);

?>
  • 写回答

3条回答 默认 最新

  • drjmrg8766 2017-02-28 10:31
    关注

    To get a single object with key/value pairs use the following simple approach:

    ...
    while ($student = pg_fetch_array($query)) {
        $json[$student["name"]] = $student["name"];
    }
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?