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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度