This is what i would like to end up with
{
name: 'creditor',
y: 5600
}, {
name: 'Supplier',
y: 2400,
}, {
name: 'Normal',
y: 1038
}, {
name: 'Suppliers',
y: 4377
},
I have tied:
$roles = AllUserRoles::find()->all();
$userdata = [];
foreach ($roles as $role) {
$name = array('name' => $role["description"]);
$trucks = TblTrucks::find()->where(['role_id'=>$role["id"]])->count();
$totals = array('y'=>$trucks);
array_push($userdata, array($name => $totals));
}
return json_encode($userdata);
But now am getting an illegal string offset at array_push
How can i generate json as above from php?
Mo Abdul-Hameed
6,1102 gold badges26 silver badges38 bronze badges
asked Aug 22, 2017 at 20:52
1 Answer 1
You have to do it like below:-
$roles = AllUserRoles::find()->all();
$userdata = [];
foreach ($roles as $role) {
$name = $role["description"];
$trucks = TblTrucks::find()->where(['role_id'=>$role["id"]])->count();
$userdata[] = ['name'=>$name,'y'=> $trucks]; // assign data directly
}
return json_encode($userdata);
answered Aug 22, 2017 at 20:55
Death-is-the-real-truth Death-is-the-real-truth
72.3k10 gold badges58 silver badges105 bronze badges
3 Comments
AbraCadaver
'y'=> $trucks
Death-is-the-real-truth
@AbraCadaver i am in the process of editing that. thanks for telling BTW
Geoff
ok i cant mark before 7 mins are over but will surely mark it.
lang-php
array_push
? A simple append$list[] = [...]
would have been easier, and avoided $name being an array.