2017-02-28 108 views
-3

我要转换的JSON文件键:值对,用于如何使用PHP或JS将JSON转换为值 - 密钥对?

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

像下面键:值对格式,这样

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

?> 

回答

1

要获得单个对象与键/值对使用以下简单的方法:

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

感谢罗马人,你解决了我的问题,最后一件事我该如何追加结果,在一个文本文件文件后r var data = {“apple”:“apple”,“Google”:“Google”,。 。 。 。 。 。 。 。 。 。 。 。 }“ –

+0

使用'file_put_contents('textvalues.txt',$ textval,FILE_APPEND)'将数据附加到文件而不是覆盖它 – RomanPerekhrest

+0

谢谢,但是当我再次运行文件时,它会附加上以前的数据。因此,如何刷新文件得到刷新前的变化 –

1

做,在这种方式(在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"},那不错。

0

只要改变而循环

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"}]