从嵌套的json数组中获取值

时间:2014-08-29 10:08:13

标签: jquery arrays json nested

我有一个json调用返回的内容:

Array
(
    [0] => Array
        (
            [so] => SO0040024
        )

    [1] => Array
        (
            [coid] => 4824
        )

    [2] => Array
        (
            [sdkstatus] => 7
        )

    [3] => Array
        (
            [sdkstatus] => pass
        )

    [4] => Array
        (
            [invoicenumber] => INV0063955
        )

    [5] => Array
        (
            [invoiceamount] => 9437.24
        )

    [6] => Array
        (
            [invoicestatus] => pass
        )

    [7] => Array
        (
            [invoicestatus] => fail
        )

)

如何从数组中提取每个值?例如,我想要invoicenumber,INV0063955。

谢谢, 莱恩

1 个答案:

答案 0 :(得分:1)

这是构建数据的可怕方式。它们应该是主数组的键,而不是将每个属性嵌套在它自己的数组中。但是,如果你坚持下去:

foreach ($array as $element) {
    if (isset($element['invoicenumber'])) {
        $invoicenumber = $element['invoicenumber'];
        break;
    }
}

你也可以把它变成一个更健全的关联数组,如下所示:

$newarray = array();
foreach ($array as $element) {
    foreach ($element as $key => $value) {
        $newarray[$key] = $value;
    }
}

然而,这不会处理重复的键,它只会保存最后一个键。我不确定如何在您的数据中处理这个问题。也许那些元素实际上应该是值数组?