更改JSON输出

时间:2012-10-19 14:07:51

标签: php mysql json mysqli

我使用以下代码从我的表中获取内容。 但我需要稍微更改JSON的输出。

$rows = array();
if(isset($_GET['fruitName'])) {
$stmt = $pdo->prepare("SELECT variety FROM fruit WHERE name = ? ORDER BY variety");
$stmt->execute(array($_GET['fruitName']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);

使用上面的代码,它显示如下:

[{"variety":"Apple"},{"variety":"Banana"},{"variety":"Orange"},{"variety":"Pear"}]

但我希望它是这样的:

[{"optionValue": "Apple", "optionDisplay": "Apple"}, {"optionValue": "Banana", "optionDisplay": "Banana"}, {"optionValue": "Orange", "optionDisplay": "Orange"}, {"optionValue": "Pear", "optionDisplay": "Pear"}]

5 个答案:

答案 0 :(得分:2)

一种解决方案可能是调整SQL查询,如下所示:

SELECT variety AS optionValue, variety AS optionDisplay FROM fruit WHERE name = ? ORDER BY variety

另一种方法是单独解析每一行并手动构建数组。而不是

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

你可以使用

$rows = array();
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
  $rows[] = array( 'optionValue' => $row['variety'], 'optionDisplay' => $row['variety'] );
}

答案 1 :(得分:0)

将您的选择语句更改为

"SELECT variety as `optionValue`,variety as `optionDisplay` FROM fruit WHERE name = ? ORDER BY variety"

答案 2 :(得分:0)

$data = '[{"variety":"Apple"},{"variety":"Banana"},{"variety":"Orange"},{"variety":"Pear"}]';

$arr = new array();
// loop through the data
foreach($data as $k => $v){
  // build an array of values formatted as you want
  $arr[] = '{"optionValue": "'.$v.'", "optionDisplay": "'.$v.'"}}';
}
// join all the values togetger, and pass through json parser
$obj = json_decode(',', "[" . implode($arr) . "]");
// should return in your desired format...

答案 3 :(得分:0)

不完全确定,因为我无法对此进行测试,但您无法将SQL语句更改为:

$stmt = $pdo->prepare("SELECT variety as optionValue, variety as optionDisplay FROM fruit WHERE name = ? ORDER BY optionDisplay");

答案 4 :(得分:0)

我不明白你为什么要这样做,但无论如何,这就是:

$new_array=array();
foreach ($rows as $row) {
array_push($new_array,array("optionValue"=>$row['variety'],"optionDisplay"=>$row['variety']));
}
echo json_encode($new_array);