【问题标题】:creating json format in php for autocomplete search在 php 中创建 json 格式以进行自动完成搜索
【发布时间】:2016-10-20 10:11:04
【问题描述】:

我想在标签和类别中创建 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(data);

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

【问题讨论】:

  • 请注意,您可以简单地在数组上使用json_encode()。您不必将其转换为任何特殊的字符串格式。

标签: php arrays json jquery-ui-autocomplete


【解决方案1】:

更新您的代码:

$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);

【讨论】:

    【解决方案2】:

    就这样

    <?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

    【讨论】:

    • 嗨,Rishi 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, 成功: function(data) {} }); } });
    • 在这里我的 ajax 调用我在 console.log 中获取 json 数据,但自动完成不起作用
    猜你喜欢
    • 2016-06-13
    • 2012-01-14
    • 2023-03-18
    • 1970-01-01
    • 2015-04-10
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    相关资源
    最近更新 更多