简体   繁体   English

读取MySQL表的列作为单独的JSON对象

[英]Reading columns of MySQL table as separate JSON object

I am reading data from a MySQL table like this: 我正在从MySQL表中读取数据,如下所示:

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. 它将整行作为tmp数组中的单个项读取,但我希望将单个列的所有值放在一个单独的数组中。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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