jquery json多维数组长度

时间:2009-11-18 21:24:09

标签: jquery arrays json

我正在使用jQuery ajax json调用将3维PHP数组检索到Javascript中。 PHP数组看起来像这样:

    $rate[0][1]['name'] = 'guff';
    $rate[0][1]['value'] = 'puff';
    $rate[0][2]['name'] = 'guff';
    $rate[0][2]['value'] = 'puff';
    $rate[0][3]['name'] = 'guff';
    $rate[0][3]['value'] = 'puff';
    $rate[1][1]['name'] = 'guff';
    $rate[1][1]['value'] = 'puff';
    $rate[1][2]['name'] = 'guff';
    $rate[1][2]['value'] = 'puff';

我试图找到子阵列的长度,例如当我从jquery ajax调用中得到这个时rate[1].length

    $.ajax({
        type: 'post',
        url: 'ajax_load_rates.php',
        data: 'trip_type='+$('#trip_type').val(),
        dataType: "json",
        success: function(dat) {
            rates = dat;
    }});

jQuery似乎转换了外部数组,因此rates.length给了我一个值。但是不转换子数组,因此rates[9].length未定义

我尝试循环遍历数组以手动转换它:

    $(rates).each(function(i) {
        rates[i] = jQuery.makeArray($(this));   
        console.log(rates[i].length);
    });

但是当我知道有负载时,我得到的值为1。

这里是json字符串的示例:

[{"1":{"name":"Single-trip base loading","value":"10","default":"0"},"2":{"name":"Multi-trip base loading","value":"50","default":"0"}},{"1":{"name":"City break","value":"70","default":"0"},"2":{"name":"Sun and sand","value":"75","default":"0"},"3":{"name":"Backpacker","value":"90","default":"0"},"4":{"name":"Horse riding","value":"120","default":"0"},"5":{"name":"Safari","value":"80","default":"0"},"6":{"name":"Golf","value":"85","default":"0"},"7":{"name":"Surf and sail","value":"140","default":"0"},"8":{"name":"Road runner","value":"130","default":"0"},"9":{"name":"Flotilla","value":"150","default":"0"},"10":{"name":"Offshore sailor","value":"200","default":"0"},"11":{"name":"Kite surfer","value":"300","default":"0"}}]

任何想法,帮助都会很棒。我对json / ajax / jQuery很新。你可以从我的代码中说出来。

欢呼声,

抢劫。

1 个答案:

答案 0 :(得分:0)

在PHP中,如果不启动索引为0的数组,则将其视为关联数组。当您使用json_encode方法时,它将成为JSON中的Object。

您可以对代码进行一些优化,但由于您只是将此作为示例,我假设您的实际代码还有很多其他内容。

这与您提供的代码相同,只有第二层元素的索引现在从零开始而不是一个

$rate[0][0]['name'] = 'guff';
$rate[0][0]['value'] = 'puff';
$rate[0][1]['name'] = 'guff';
$rate[0][1]['value'] = 'puff';
$rate[0][2]['name'] = 'guff';
$rate[0][2]['value'] = 'puff';
$rate[1][0]['name'] = 'guff';
$rate[1][0]['value'] = 'puff';
$rate[1][1]['name'] = 'guff';
$rate[1][1]['value'] = 'puff';

将其传递给json_encode会产生以下结果:

[[{"name":"guff","value":"puff"},{"name":"guff","value":"puff"},{"name":"guff","value":"puff"}],[{"name":"guff","value":"puff"},{"name":"guff","value":"puff"}]]

您可以看到第二级元素仍然是JSON([])中的数组而不是对象({})。