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

how to convert JSON to Value-Key Pair using PHP or JS?

我想将 JSON 文件转换为 key:value 对,即

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

像下面key:value对格式,像这样

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

所以任何人都可以告诉我我该怎么做,下面是 Php 文件代码,其中我从 psql 数据库中获取数据并将其存储在一个文件中。

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);

?>

这样做(在foreach):

    $obj = new stdClass(); 
    $obj->label=1; 
    $obj->value=2;
    $json[]=$obj;

    $obj = new stdClass(); 
    $obj->label=3; 
    $obj->value=4;
    $json[]=$obj;

    print_r(json_encode($json));

结果[{"label":1,"value":2},{"label":3,"value":4}]

或仅针对一个对象

    $obj = new stdClass();

    $array = [['name'=>'test'],['name'=>'foo']];

    foreach($array as $var)
      $obj->{$var['name']}=$var['name']; 

    print_r(json_encode($obj));

结果{"test":"test","foo":"foo"}

注意:我在这里使用stdClass,所以大家可以直接看到它在json(也是一个对象)中会变成什么,并且不应该与索引键一起使用。 print_r(json_encode([1,'foo'=>'sadsd'])); 会变成 {"0":1,"foo":"sadsd"},有什么不好的。

要获得具有 key/value 对的单个对象,请使用以下简单方法:

...
while ($student = pg_fetch_array($query)) {
    $json[$student["name"]] = $student["name"];
}
...

只需更改 while 循环

while($student=pg_fetch_array($query)){
$student_name=$student['name'];
$res[$student_name] =$student_name;
 array_push($json,$res);
 }
echo json_encode($return_arr);

这将 return 一个 json 格式的字符串:

[{"xyz":"xyz"},{"abc":"abc"}]