1

我使用以下代码从我的表中获取内容。但我需要稍微改变一下 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"}]
4

5 回答 5

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'] );
}
于 2012-10-19T14:18:38.800 回答
0

将您的选择语句更改为

"SELECT variety as `optionValue`,variety as `optionDisplay` FROM fruit WHERE name = ? ORDER BY variety"
于 2012-10-19T14:16:09.160 回答
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...
于 2012-10-19T14:16:24.027 回答
0

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

$stmt = $pdo->prepare("SELECT variety as optionValue, variety as optionDisplay FROM fruit WHERE name = ? ORDER BY optionDisplay");
于 2012-10-19T14:17:51.790 回答
0

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

$new_array=array();
foreach ($rows as $row) {
array_push($new_array,array("optionValue"=>$row['variety'],"optionDisplay"=>$row['variety']));
}
echo json_encode($new_array);
于 2012-10-19T14:20:08.923 回答