PHP json_encode无法使用1维数组

时间:2015-03-02 16:20:24

标签: javascript php arrays json pdo

我使用jquery-autocomplete插件从建议/自动完成中查找数组。

参考:https://github.com/devbridge/jQuery-Autocomplete

PHP(1)

$stmt = $dbh->query("SELECT tag_name FROM tags");
$tags = array();
$tags = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
echo json_encode($tags);
/*
    var_dump($tags);
    "array(6) {
      [0]=>
      string(1) "tag1"
      [1]=>
      string(2) "tag2"
      [2]=>
      string(3) "tag3"
      [3]=>
      string(4) "tag4"
    }
    "
*/

PHP(2)

echo ('["tag1","tag2","tag3","tag4"]');

PHP(3)

$a = ["tag1","tag2","tag3","tag4"];
echo json_encode($a);

的JavaScript

$.ajaxSetup({ cache: false, async: false });

var myTags = [];
$.get( '/action.php', {action: 'get_tags'}).done( function(data){
  console.log(data);
  myTags = eval(data);
  //myTags = JSON.parse(data);
});

$('#tagInput').autocomplete({
  lookup: myTags
});

PHP v1和PHP v2都将提供正确的数组console.log(data)。 但是,来自PHP v1 json_encode($tags)的数组不能使用该插件(它根本无法识别该数组)。虽然PHP v2数组echo ('["tag1","tag2","tag3","tag4"]');工作得很好。 PHP v3也不会工作。

此代码有什么问题?为什么json_encode()数组未被识别?

2 个答案:

答案 0 :(得分:1)

该插件不会接受' (可能是一个错误)数组如果数组中包含一个单个字符串的字符串:

['tag1','a','tag2','tag3'] // won't work
['tag1','tag2','tag3'] // works

所以,PHP json_encode都没问题。

答案 1 :(得分:0)

您的v2之所以有效,是因为您使用了一系列字符串来表达建议,例如:

{
  "query": "Unit",
  "suggestions": ["United Arab Emirates", "United Kingdom", "United States"]
}

当你要提供数据时,字符串数组的直接json_encode不起作用。你需要一个特殊的结构:

{
  // Query is not required as of version 1.2.5
  "query": "Unit",
  "suggestions": [
      { "value": "United Arab Emirates", "data": "AE" },
      { "value": "United Kingdom",       "data": "UK" },
      { "value": "United States",        "data": "US" }
  ]
}