简体   繁体   中英

creating a json output in php

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM