doumao8355 2013-02-19 13:30
浏览 13
已采纳

如何使用AJAX搜索PHP多维数组

I have a multidimensional array with which I want to search for values and keys using this

<input type="text" onkeyup="showHint(this.value)"></input>

along with this

function showHint(str)
{
if (str.length==0)
  { 
  document.getElementById("nav").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("nav").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}

I am just a bit stuck on the php bit. The array looks something like this (shortened)

Array
(
[Modest Mouse] => Array
  (
  [The Moon & Antarctica] => Array
    (
    [0] => 3rd Planet
    [1] => Gravity Rides Everything
    [2] => Dark Centre of the Universe
    )
  [The Lonesome Crowded West] => Array
    (
    [7] => Cowboy Dan
    [8] => Trailer Trash
    [9] => Out of Gas
    )
[The Vasco Era] => Array
  [Lucille] => Array
    (
    [0] => Not Stuck Here
    [1] => For No One
    )
  )
)

I start by getting the query

$q=$_GET["q"];

Then I can do this

if (strlen($q) > 0)
    {
    $hint="";
    foreach($a as $b => $c)
        {
        if (strtolower($q)==strtolower(substr($b,0,strlen($q))))
            {
            if ($hint=="")
                {
                $hint=$b;
                }
            else
                {
                $hint=$hint." , ".$b;
                }
            }
         }
      }

Which can get me Modest Mouse or The Vasco Era, but not anything deeper. If I were to type 'T' into the input field, I would like to be able to get the results 'The Moon & Antartica', 'The Lonesome Crowded West', 'Trailer Trash' and 'The Vasco Era'.

  • 写回答

1条回答 默认 最新

  • dqyym3667 2013-02-19 13:36
    关注

    You can have a function that takes a variable and checks if it is an array, if it is an array loop through each element of the array. Subsequently if these elements are arrays recursively call back into this function, if they are not arrays then run your comparison as shown above.

    function checkForHint($var)
    {
        foreach ($var as $value) {
            if(is_array($value))
            {
                checkForHint($value);
            } else {
                // Your code here
            }
        }
    }
    

    Something like that, perhaps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决