codeigniter-restserver
codeigniter-restserver copied to clipboard
Problem when passing an array of objects to REST_Controller::response() for HTML and CSV formats
I had a problem when passing an array of objects as data to response() method: the method was treating as a single dimensional array and the output was broken
e.g. for the array
$data = array(
array(
'id' => 0,
'name' => 'test0'
),
array(
'id' => 1,
'name' => 'test1'
),
array(
'id' => 2,
'name' => 'test2'
)
);
response in html
<table border="0" cellpadding="4" cellspacing="0">
<thead>
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
I solve the problem adding this code to Format class, to methods to_html() and to_csv(), in Check if it's a multi-dimensional array
...
// Check if it's an array of objects
elseif (isset($data[0]) && is_object($data[0]))
{
// Convet to multi-dimensional array
$data = json_decode(json_encode($data), true);
$headings = array_keys($data[0]);
}
...
Update change
$data = json_decode(json_encode($data), true);
to
$data = $this->to_array($data);
because to_array() is a method of Format class and is more efficient then JSON encode-decode
Ultimately, we are just passing the arrays to the CI functions.