Anders Gerner Anders Gerner - 1 month ago 12
JSON Question

How to fix JSON result where headers is separated from values in 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 :)

Answer

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.