Reputation: 361
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. e.g 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?
Upvotes: 0
Views: 92
Reputation: 65274
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);
Upvotes: 2