I'm want to retrieve and insert an array of images inside an array of projects. My array of projects has this config:
Array (
[projectos] => Array (
[0] => stdClass Object (
[id_projecto] => 1
[titulo] => Titulo do projecto
[descricao] => Descrição
[data] => 0000-00-00
[id_categoria] => 3
)
[1] => stdClass Object (
[id_projecto] => 5
[titulo] => Teste
[descricao] => Teste
[data] => 2014-07-02
[id_categoria] => 2
)
[2] => stdClass Object (
[id_projecto] => 7
[titulo] => Teste Projecto
[descricao] => Yo
[data] => 2014-07-02
[id_categoria] => 3
)
)
)
And this is how I made the loop to retrieve images and insert an array inside each project.
for ($i = 0; $i < count($data['projectos']); $i++)
{
$data['projectos'][$i]['imagens'][] = $this->imagem_model->get_many_by('id_projecto', $data['projectos'][$i]->id_projecto);
}
The result of this is a blank page which in CodeIgniter very often means an error in PHP syntax which I can't see how!
The get_many_by()
function is working fine and it's not the problem. I'm using CodeIgniter Framework, the latest release.
Note: if I use this loop, the result is fine but it's not with the data format I want:
foreach ($data['projectos'] as $row)
{
$data['projectos']['imagens'][] = $this->imagem_model->get_many_by('id_projecto', $row->id_projecto);
}
You're trying to access an object like an array. $data['projectos'][$i]['imagens']
should be more like $data['projectos'][$i]->imagens
... and you need to declare that class to have that public variable, initialized as an empty array before you try to append to it.
$data['projectos'][$i]->imagens = array();
// ...
$data['projectos'][$i]->imagens[] = 'a value';
But why do that? I suspect the get_many_by
function already returns an array. So all you need to do is change your for
loop to contain this declaration so that the array is just assigned to this Object variable:
$data['projectos'][$i]->imagens = $this->imagem_model->get_many_by('id_projecto', $data['projectos'][$i]->id_projecto);