自动完成中的PHP json_encode

时间:2016-10-06 10:12:51

标签: php json

我有

<form action='' method='post'>
  City name <br /><br />
  <input type='text' name='search' value='' class='auto'>
</form>

<script type="text/javascript">
  $(function() {

    //autocomplete
    $(".auto").autocomplete({
        source: "search.php",
        minLength: 1
    });

  });
</script>

这是自动完成的。现在我在search.php文件中接收来自MySQL库的字段:

if(isset($_GET['term']))
    {
        $city = array();
        $airport = array();
        $citysearchsql = mysqli_query(db(),"SELECT * FROM citycode WHERE cityname LIKE '%".$_GET['term']."%' ");
        while($citysearchresult = mysqli_fetch_array($citysearchsql))
        {



            $airnamesql = mysqli_query(db(),"SELECT * FROM airports WHERE citycode='".$citysearchresult['citycode']."' ");
            while($airnameresult = mysqli_fetch_array($airnamesql))
            {
                $airport[] = $airnameresult['airportname'];
            }
            $city[] = $citysearchresult['cityname'];
        }




        echo json_encode($city);

    }

Base有两个表citycodeairports。当用户写城市名称时,需要显示城市名称和城市名称下显示机场名称,如此处

http://joxi.ru/krD8oY1u0Nb0kr

我无法使用json_encode

任何想法,任何人都可以帮助我

3 个答案:

答案 0 :(得分:2)

获取数组中的所有必需元素,然后您可以在前端和显示中使用自己的自定义数据格式,只需覆盖默认焦点并选择操作。

$("#autocomplete").autocomplete()
.data( "autocomplete" )._renderItem = function( ul, item ) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( item.label )
        .appendTo( ul );
};

Check this link for demo example

答案 1 :(得分:0)

是的,你可以......只是合并表格

echo json_encode(array_merge($city, $airport));

答案 2 :(得分:0)

优化为一个查询:

if (isset($_GET['term'])) {
        $city = array();
        $citysearchsql = mysqli_query(db(),"SELECT a.airportname, c.cityname FROM citycode c INNER JOIN airports a ON c.citycode = a.citycode WHERE c.cityname LIKE '%".$_GET['term']."%' ORDER BY c.citycode ASC");
        while($citysearchresult = mysqli_fetch_array($citysearchsql))
        {
            if (!in_array($citysearchresult['cityname'], $city)) {
                $city[] = $citysearchresult['cityname'];
            }
            $city[] = $citysearchresult['airportname'];   
        }
        echo json_encode($city);
}