Skip to content
Advertisement

how to create multi array in foreach CI without loop all

I have a problem from foreach to array why is everything loop?

example output json i want.

{"page":"books","list":[{"title":"ABC"},{ "title" : "CDE"}]}

example output from my code

{"page":"books","list":[{"title":"ABC"}]}{"page":"books","list":[{"title":"CDE"}]}

this my code

foreach ($row as $rows) :
        $arrayName = array(
            'page' => $this->input->get('type', TRUE),
            'list' => array([
                'title' => $rows['title'],
            ])
        );
        echo json_encode($arrayName);
endforeach;

and this my CI_Controller

return $this->db->get()->result_array();

how to loop only in “list :” line only?

Advertisement

Answer

Don’t encode in every loop iteration, create your array in the format you want and then encode it to json.

$arrayName = [];
$arrayName['page'] = $this->input->get('type', TRUE);
foreach ($row as $rows) :  
        $arrayName['list'][] = [
                'title' => $rows['title']
            ];
endforeach;
        echo json_encode($arrayName);

In the above code you create your array and the static field page outside of the loop, you don’t need it inside the loop.

The field that includes nested arrays is the list so you basically create nested arrays with key title and title value for each iteration.

When you are done you simply encode your overall array and you will end up with your expected output

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement