drgm51600 2016-10-18 12:46
浏览 33
已采纳

如何修复JSON结果,其中标头与PHP中的值分开

I have a JSON result from a webservice, which is for some crazy reason, created like a table. See:

{
"headers": [
    "field_a",
    "field_b",
    "field_c"
],
"rows": [
    [
        "value 1",
        123.212,
        true
    ],
    [
        "value 2",
        542,
        false
    ],
    [
        "value 3",
        342,
        false
    ],
    [
        "value 4",
        5452,
        false
    ],
    [
        "value 5",
        32,
        true
    ]
],
"totalRows": 5
}

This sucks to work with, since I cant say $json->field_a, but instead I need to loop the "rows" in a foreach and access it as an array like $json => $obj {$obj[0]} to get the first value.

I'm trying to create a function like:

function fixOutput($jsonResponse){
$newResponse = array_combine(array_values($jsonResponse->headers), array_values($jsonResponse->rows));
}

But it give the warning:

Warning: array_combine(): Both parameters should have an equal number of elements

So, before I spend hours trying to find the correct solution, is there somebody how can help me, creating this method, the most memory-wise optimal way, since the JSON responses I'll get in production will have between 10 and 2000 rows.

Thanks in advance, guys :)

  • 写回答

1条回答 默认 最新

  • dopnpoh056622 2016-10-18 12:56
    关注

    Your function does not work because you are trying to combine the contents of the $jsonResponse->rows array with the $jsonResponse->headers, instead of combining each element of the $jsonResponse->rows array with the headers.

    I would just use a plain old foreach loop.

    $data = [];
    $headers = $jsonResponse->headers;
    $nrOfHeaders = count($headers);
    
    foreach ($jsonResponse->rows as $row) {
        $newRow = [];
        for($i = 0; $i < $nrOfHeaders; $i++) {
            $newRow[$headers[$i]] = $row[$i];
        }
        $data[] = $newRow;
    }
    

    data now is an array containing associative arrays. You can trivially modify this example to use stdClass objects instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?