简体   繁体   中英

Reading columns of MySQL table as separate JSON object

I am reading data from a MySQL table like this:

while($row=mysql_fetch_assoc($result))
{
   $tmp[]=$row;
}

It reads whole row as a single item in the tmp array, but I want all values of a single column together in a separate array. eg if I the table is:

     -------------------
      Honda  Suzuki  BMW
     -------------------
      Accord  Alto   abc
      Acty    Baleno xyz

I get this:

     [{"Honda":"Accord","Suzuki":"Alto","BMW":"abc"},
      {"Honda":"Acty","Suzuki":"Baleno","BMW":xyz"}]

but I want this:

     [ Honda:{Accord,Acty},
       Suzuki:{Alto,Baleno},
       BMW:{abc,xyz}
     ]

Can somebody tell how should I structure the data like this?

I suspect you mean

{ "Honda":["Accord","Acty"],
  "Suzuki":["Alto","Baleno"],
  "BMW":["abc","xyz"]
}

which you would get by

$tmp=array();
while($row=mysql_fetch_assoc($result))
  foreach($row as $name=>$value)
    //Next 2 lines updated after input from comment
    if (!$value) continue;
    else if (!isset($tmp[$name])) $tmp[$name]=array($value);
    else $tmp[$name][]=$value;
$tmp=json_encode($tmp);

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