codeigniter-restserver icon indicating copy to clipboard operation
codeigniter-restserver copied to clipboard

Problem when passing an array of objects to REST_Controller::response() for HTML and CSV formats

Open TenshiZer0 opened this issue 8 years ago • 2 comments

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]);
}
...

TenshiZer0 avatar Jan 17 '18 01:01 TenshiZer0

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

TenshiZer0 avatar Jan 17 '18 14:01 TenshiZer0

Ultimately, we are just passing the arrays to the CI functions.

chriskacerguis avatar Feb 27 '18 21:02 chriskacerguis