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.

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

报告相同问题?

悬赏问题

  • ¥23 (标签-bug|关键词-密码错误加密)
  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决