0
我得到的數據從DB中設置類似搜索值
Array (
[0] => Array (
[picID] => 175
[owner] => [email protected]
[likedname] => test name
[likedUriTN] => g1.jpg
[date] => 2013-05-11 09:16:17
)
[1] => Array (
[picID] => 179
[owner] => [email protected]
[likedname] => Paul
[likedUriTN] => g2.jpg
[date] => 2013-05-11 09:04:58
)
[2] => Array (
[picID] => 173
[owner] => [email protected]
[likedname] => Joseph
[likedUriTN] => j.jpg
[date] => 2013-05-09 19:44:58
)
[3] => Array (
[picID] => 175
[owner] => [email protected]
[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,只是在添加likedname陣列
這裏是從我的結果,我想要什麼
[{
"picID" : "175",
"owner" : "[email protected]",
**"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);