在php中创建json格式以进行自动完成搜索

时间:2016-10-20 10:11:04

标签: php arrays json jquery-ui-autocomplete

我想在标签和类别中创建json格式。     我没有在PHP中获得JSON格式的代码     怎么做

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

foreach ($arr as $key => $value) {

  $data = 'label:'. $key.','.'category:'.$value;
}
echo json_encode($data);


I want to something like :  
    "[{label:"a", category:"1"},{label:"b", category:"2"},{label:"c", category:"3"}]

jQuery.ui.autocomplete不起作用::

var test_url = Drupal.settings.url +'/ all_list';

jQuery(".class").catcomplete({
        delay: 500,
        minLength: 3,
       // source:data
        source: function(request, response) {
        $.ajax({
        dataType: "json",
        type : 'Get',
        url: test_url,
        success: function(data) { console.log(data);}

      });
   }

    });

我通过console.log(数据)获取;

[{"label":"a","category":1},{"label":"b","category":2},   {"label":"c","category":3},{"label":"d","category":4},{"label":"e","category":5}]

2 个答案:

答案 0 :(得分:0)

更新您的代码:

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

foreach ($arr as $key => $value) {

    $data .= 'label:'. $key.','.'category:'.$value; //you have missed this concatenation part
}
echo json_encode($data);

答案 1 :(得分:0)

就像这样

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$final = array();
foreach($arr as $key=>$value){
  $final[]=["label"=> $key,"category" => $value];
}
echo json_encode($final);
?>

输出是:

[{"label":"a","category":1},{"label":"b","category":2},{"label":"c","category":3},{"label":"d","category":4},{"label":"e","category":5}]

现场演示:https://eval.in/663626