1

我有一个需要搜索的 JSON 数组:

[
{
      "Device_ID":"1",
      "Image":"HTC-One-X.png",
      "Manufacturer":"HTC",
      "Model":"One X",
      "Region":"GSM",
      "Type":"Phone"
   },
   {
      "Device_ID":"2",
      "Image":"Motorola-Xoom.png",
      "Manufacturer":"Motorola",
      "Model":"Xoom",
      "Region":"CDMA",
      "Type":"Tablet"
   },
   {
      "Device_ID":"8",
      "Image":"null",
      "Manufacturer":"Motorola",
      "Model":"Xoom 2",
      "Region":"CDMA",
      "Type":"Tablet"
   }
]

使用关键字:$_GET['keyword'];我需要能够执行以下操作。搜索制造商和型号的组合值,即。摩托罗拉 Xoom。然后,对于与此匹配的任何一组值,将它们输出到变量。

例如:如果关键字是 HTC,那么它将搜索数组并输出:

$DeviceID = 1 $Image = HTC-One-X.png $Manufacturer = HTC $Model = One
X $Region = GSM $Type = Type

但是,如果关键字是 Motorola,则需要输出包含 Motorola 的所有条目。

当用户键入关键字时,我试图做的是输出所有 JSON 数组条目的实时视图。但是我希望它在用户计算机上运行以减少服务器上的负载。

有谁知道解决这个问题的最佳方法?

4

2 回答 2

1

well if you have a selection box with the values for the manufacturer in the options section it's as easy as:

HTML:

<select id="selectionBox">
  <option>...</option>
</select>
<div id="outPut">
  output goes in here
</div>

Javascript:

var selectedValue = document.getElementById("selectionBox").value;
for(var i = 0; i < jsonObject.length; i++){
  if(jsonObject[i].Manufacturer === selectedValue){
    //considering your object is an array let's
    for(var key in jsonObject[i]){
      document.getElementById("outPut").innerHTML += jsonObject[i][key] + "</br>";
    }
  }
}

that'll pretty much print everything in the object onto the output div, the rest is up to your styling.

于 2012-05-10T15:33:41.190 回答
1

这是一个过滤 JSON 的函数。显示数据由您决定。

var devices = <your JSON array>;    

function filter(keyword, data) {
    var filteredArray = [], i, j;
    for (i = 0, j = data.length; i < j; i++) {
        if ((data[i].Manufacturer && data[i].Manufacturer.indexOf(keyword) !== -1) || (data[i].Model && data[i].Model.indexOf(keyword) !== -1)) {
            filteredArray.push(data[i]);
        }
    }
    return filteredArray;
}

// Example usage
var MotorolaDevices = filter('Motorola', devices);
于 2012-05-10T16:03:30.997 回答