Mysql PHP多维数组



我有这个mysql结果:

pic  userid   username
 A     1       peter
 A     2       jack
 B     3       maria
 B     4       anna

我想要一个像这样的多维数组:

{"pics": 
   {"pic" => "A", "users" => [
                     {"userid" => "1", "username" => "peter"}, 
                     {"userid" => "2", "username" = "jack"}
                   ],
    "pic" => "B", "users" => [
                     {"userid" => "3", "username" => "maria"}, 
                     {"userid" => "4", "username" = "anna"}
                   ]}

谢谢!

我试过了:

$result=mysql_query("SELECT A.pic, B.userid, B.username FROM `tabpics` A LEFT JOIN tabuser B ON (A.userid = B.userid)");
while ($date=mysql_fetch_array($result)){
$pics[$date['pic']][] = array("userid"=>$date['userid'],"username"=>$date['username']);
} 

,结果如下:

{"A"=> {"userid" => "1", "username" => "peter"}, "A" => {"userid" => "2", "username" = "jack"} ....

请尝试一下

$userArr = "";
$result=mysql_query("SELECT A.pic, B.userid, B.username FROM `tabpics` A LEFT JOIN tabuser B ON (A.userid = B.userid)"); 
while ($data=mysql_fetch_array($result)){
    $userArr[$data['pic']][] = array("userid"=>$data['userid'],"username"=>$data['username']); 
}
if(count($userArr) > 0){
    foreach ($userArr as $picName => $valArr) {
        $pics[]=array("pic" => $picName ,"users" => $valArr);
    }
}
echo "<pre>";
print_r($pics);

相关内容

  • 没有找到相关文章

最新更新