从嵌套的json数组中获取值

时间:2021-01-26 13:42:14

I have the follwoing being returned by a json call:

我有一个json调用返回的follwoing:

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
        )

)

How do I extract each value out of the array? for example I want invoicenumber, INV0063955.

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

Thanks, Ryan

谢谢,瑞恩

1 个解决方案

#1


1  

That's a horrible way to structure your data. Instead of nesting each property in its own array, they should be keys of the main array. But if you're stuck with it:

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

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

You could also turn it into a more sane associative array like this:

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

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

However, this won't deal with the repeated keys, it will just save the last one. I'm not sure how this is supposed to be handled in your data. Maybe those elements should actually be arrays of values?

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

#1


1  

That's a horrible way to structure your data. Instead of nesting each property in its own array, they should be keys of the main array. But if you're stuck with it:

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

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

You could also turn it into a more sane associative array like this:

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

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

However, this won't deal with the repeated keys, it will just save the last one. I'm not sure how this is supposed to be handled in your data. Maybe those elements should actually be arrays of values?

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