PHP Laravel 4 Array to nested JSON -
i using laravel 4
. @ beginner stage not aware of features of php
laravel
framework.
i have array fetched table below :
$result = model::all();
that gives :
[0]=>[ [id]=>1 [name]=>"abc" [description]="temp" [tempfield1]="t1" [tempfield2]="t2" [tempfield3]="t3" ] [1]=>[ [id]=>1 [name]=>"xyz" [description]="temp2" [tempfield1]="t21" [tempfield2]="t22" [tempfield3]="t23" ] ... , on.
now, want generate json array :
"items":[{ "id": 1, "name":"abc", "description":"temp", "temps":[{ "temp1":"t1", "temp2":"t2", "temp3":"t3", }] }, { "id": 2, "name":"xyz", "description":"temp2", "temps":[{ "temp1":"t21", "temp2":"t22", "temp3":"t23", }] } ... , on ]
to achieve this, have created item class have properties id, name , description.
class item{ public $id; public $name; public $description; }
also have created temp class extends item class , having properties temp1, temp2 , temp3.
class temp extends item{ public $temp1; public $temp2; public $temp3; }
what idea create list of type class temp
, create foreach
loop fetch each record array given above , populate object of temp
class respective properties , push object list. example,
$list = array(); foreach ($result $row){ $objtemp = new temp(); $objtemp->id = $row["id"]; $objtemp->name = $row["name"]; $objtemp->description= $row["description"]; $objtemp->temp1= $row["tempfield1"]; $objtemp->temp2= $row["tempfield2"]; $objtemp->temp3= $row["tempfield3"]; list->push($objtemp); }
and idea convert list json. failed achieve so. print_r($objtemp)
gives me list flat structure, not nested temp fields.
can me achieve nested json using flat array please?
thanks in advance..
in controller put:
return response::json($result);
but should define relationship between item , temp (something like):
class item extends eloquent{ public $id; public $name; public $description; public function temps() { return $this->hasmany('temp','user_id', 'user_id'); } }
Comments
Post a Comment