我正在从MySQL表中读取数据:
while($row=mysql_fetch_assoc($result))
{
$tmp[]=$row;
}
它将整行作为tmp
数组中的单个项目读取,但我希望将单个列的所有值放在一个单独的数组中。例如,如果我的表是:
-------------------
Honda Suzuki BMW
-------------------
Accord Alto abc
Acty Baleno xyz
我明白了:
[{"Honda":"Accord","Suzuki":"Alto","BMW":"abc"},
{"Honda":"Acty","Suzuki":"Baleno","BMW":xyz"}]
但我想要这个:
[ Honda:{Accord,Acty},
Suzuki:{Alto,Baleno},
BMW:{abc,xyz}
]
有人可以告诉我应该如何构建这样的数据?
答案 0 :(得分:2)
我怀疑你的意思
{ "Honda":["Accord","Acty"],
"Suzuki":["Alto","Baleno"],
"BMW":["abc","xyz"]
}
你会得到
$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);