在 javascript 中检索多维 json 数组

Retrieving multidimensional json array in javascript

本文关键字:json 数组 检索 javascript      更新时间:2023-09-26

我知道关于这个话题有很多问题和答案,但没有一个能回答我的具体问题 - 我已经搜索和兜圈子一个月了!

我使用 php 从 may 数据库中获取值并通过 json 返回:

    $staff_list = array(
          "name" => $staff_names,
          "id" => $staff_ids,
          "img" => $staff_imgs,
          "typeID" => $staff_types,
    );
    print(json_encode($staff_list));

我正在拉入一个javascript:

$.getJSON(requestURL, function(data) {
    if( data.errorResponse ) {
            element.html("<p>(" + data.errorResponse.message + ")</p>");
    } else {
        $('#designeesloading').remove();
        $.each(data, function(i, field){
            $.each(field, function(x, value){
                haystack.push({
                  i:value //this should put into 4 arrays as per above shouldn't it?
                });
            });
        });

    } //errorResponse else
  }); //getJSON
但是,当我

在这里提取时,它不是 25 个元素(因为有 25 个名称、图像等),它会经历 100 次(我想是 4 次 x 25):

(每次有人在搜索框中键入内容时都会触发):

    $.each(haystack, function(i,v) { //this goes through 100 times instead of 25
    if ((v['name'].toLowerCase().indexOf(needle) >= 0)) {
      choices.push({ //only want to add to choices if what they are searching for is found
        "id":v['id'],
        "name":v['name'],
        "typeID":v['typeID'],
        "img":v['img']
      });
      resultflag++;
    }
    });

如果有人想看,它就在这里。 令人沮丧的是,我会在 PHP 中在 5 分钟内完成此操作。

http://cybril.com/donation/donate.php

提前感谢任何帮助。

你的代码有两个问题。首先,你只是把所有东西都推到haystack上,你没有创建嵌套的对象来容纳每个工作人员。其次,在像 { key: val } 这样的对象文字中,i不被评估,则将其视为文字名称;仅评估val。如果要使用计算键,则必须使用方括号表示法。

    $.each(data, function(i, field){
        $.each(field, function(x, value){
            if (!haystack[x]) {
                haystack[x] = {};
            }
            haystack[x][i] = value;
        });
    });