我从DB获取数据集
Array (
[0] => Array (
[picID] => 175
[owner] => xxx@xxx.com
[likedname] => test name
[likedUriTN] => g1.jpg
[date] => 2013-05-11 09:16:17
)
[1] => Array (
[picID] => 179
[owner] => xxx@xxx
[likedname] => Paul
[likedUriTN] => g2.jpg
[date] => 2013-05-11 09:04:58
)
[2] => Array (
[picID] => 173
[owner] => xxx@xxx
[likedname] => Joseph
[likedUriTN] => j.jpg
[date] => 2013-05-09 19:44:58
)
[3] => Array (
[picID] => 175
[owner] => xxx@xxx
[likedname] => David
[likedUriTN] => g1.jpg
[date] => 2013-05-07 14:56:26
)
)
这是我的代码,
if ($result){
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows[] = array('picID'=>$r['picID'],
'owner'=>$r['owner'],
'likedname'=>$r['likedname'],
'likedUriTN'=>$r['likedUriTN'],
'date'=>$r['date']);
}
echo json_encode($rows);
}
但是,我想通过picID进行分组,只需在数组中添加likesname
这是我想要的结果
[{
"picID" : "175",
"owner" : "xxx@xxx",
**"likedname" : [{
"0" : "test name",
"1" : David
}],
"date" : "2013-05-11 09:16:17"
}, {
"picID" : "179",
...
}]
我搜索了关于数组的php,但我还没有任何线索。
这是解决方案。
我用antoox的建议进行了修改。谢谢antoox。
$rows = array();
while($r = mysql_fetch_assoc($result)) {
if (array_key_exists($r['picID'], $rows)) {
$rows[$r['picID']]['likedname'][] = $r['likedname'];
}
else {
$rows[$r['picID']] = array( 'picID'=>$r['picID'],
'owner'=>$r['owner'],
'likedname'=>array($r['likedname']),
'likedUriTN'=>$r['likedUriTN'],
'date'=>$r['date']);
}
}
echo json_encode($rows);
答案 0 :(得分:0)
你可以这样做:
if($result){
$rows = array();
$likedEmail = array();
while($r = mysql_fetch_assoc($result)) {
if (isset($rows[$r['picId']])) {
$rows[$r['picId']]['likedname'][] = $r['likedname'];
}
else {
$rows[$r['picId']] = array(
'picID'=>$r['picID'],
'owner'=>$r['owner'],
'likedname'=>array($r['likedname']),
'likedUriTN'=>$r['likedUriTN'],
'date'=>$r['date']
);
}
}
echo json_encode($rows);
}
使用 picId 作为密钥存储阵列,以确保未插入两次 picId 。