1

这与之前询问的需要在 JSON 输出中仅显示数组值有关。

我只想显示像这样的值

[
"autoComplete",
"ColdFusion",
"jQuery Mobile"
];

背景:我正在通过 Jquery mobile 使用 AJAX 调用从服务器检索数据(语言:PHP)。我想在我的 Phonegap 应用程序中使用https://github.com/commadelimited/autoComplete.js 。

请指教!我是 JSON 新手。

4

2 回答 2

1

使用 json_encode 时,任何具有从零开始的数字索引的数组(这意味着它不是关联数组并且以 0 开头并且不缺少任何数字)将被转换为 javascript 数组而不是 js 对象字面量。您可以在 php 中使用 array_values 从数字索引的数组中获取所有值。

<?php
//a generic array
$a = array(
    'foo'=>'bar',
    'one'=>'two',
    'three'=>'four');

//display the array in php
var_dump($a);
echo '<br>';

//json encode it
$json = json_encode($a);
var_dump($json);
echo '<br>';

//json encode just the values
$json = json_encode(array_values($a));
var_dump($json);

http://codepad.viper-7.com/hv06zn

于 2013-02-27T17:27:10.307 回答
0

谢谢乔纳森。

但是我找到了如下解决方案。我希望它对其他人也有用。

$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();

while($row = mysql_fetch_assoc($result)) {
  $records[] = $row["title"];
}


mysql_close($con);
echo json_encode($records);
于 2013-02-27T17:41:30.757 回答