【问题标题】:how to convert JSON to Value-Key Pair using PHP or JS?如何使用 PHP 或 JS 将 JSON 转换为值键对?
【发布时间】:2017-02-28 10:20:47
【问题描述】:

我想将 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);

?>

【问题讨论】:

    标签: php json search key-value


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢 Roman,你解决了我的问题,最后一件事我怎样才能在 var data = {"apple":"apple","Google":"Google 之后的文本文件文件中附加结果", . . . . . . . . . . . . } "
    • 使用file_put_contents('textvalues.txt', $textval, FILE_APPEND) 将数据附加到文件而不是覆盖它
    • 谢谢,但是当我再次重新运行文件时,它会附加以前的数据。那么如何在文件刷新时刷新之前的更改
    • @MDShahrouq,好吧,如果您需要覆盖文件,您的初始方法 file_put_contents('textvalues.txt', $textval); 将起作用
    • 谢谢,它成功了。我像这样使用 $foo = "var countries=" 。 $textval;
    【解决方案2】:

    这样做(在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'=&gt;'sadsd'])); 会变成 {"0":1,"foo":"sadsd"},有什么不好的。

    【讨论】:

      【解决方案3】:

      只需更改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);
      

      这将返回此格式的 json 字符串:

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

      【讨论】:

        猜你喜欢
        • 2016-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-01
        • 2021-12-15
        • 2020-08-30
        • 1970-01-01
        • 2021-04-03
        相关资源
        最近更新 更多