0

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
  • Why did you decide on array_push? A simple append $list[] = [...] would have been easier, and avoided $name being an array. Commented Aug 22, 2017 at 20:56

1 Answer 1

2

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

3 Comments

'y'=> $trucks
@AbraCadaver i am in the process of editing that. thanks for telling BTW
ok i cant mark before 7 mins are over but will surely mark it.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.