dongyan8896 2012-07-13 00:09
浏览 37
已采纳

从MySQL结果中在PHP中的while循环中向数组添加值

Sorry for the beginners question.
I've searched for an hour now, and can only find info on adding 1 key => value inside the while loop. I'm aiming for this result. Thanks

$menu = array(  
    '1' => array('id' => 1, 'parentid' => 0, 'title' => 'Apple'),  
    '2' => array('id' => 2, 'parentid' => 0, 'title' => 'Banana'),  
    '3' => array('id' => 3, 'parentid' => 0, 'title' => 'Tangerine'),  
    '4' => array('id' => 4, 'parentid' => 3, 'title' => 'Pear')
);


I've tried a number of things but this seems to be the closest.

$menu = array();
while($row = mysql_fetch_array($query)) {
    $menu[] = $row['id'] ;
    $menu[] = $row['parentid'] ;
    $menu[] = $row['title'];
}
  • 写回答

2条回答 默认 最新

  • dongwen4487 2012-07-13 00:13
    关注

    Ahh, looks like you want something like

    $menu = array();
    while ($row = mysql_fetch_array($query)) {
        $menu[] = array(
            "id" => $row['id'], 
            "parentid" => $row['parentid'], 
            "title" => $row['title']
        );
    }
    

    Associative array keys are created using "key" => "value".


    Edit

    Off topic a bit, but I'd strongly recommend learning PDO for your queries. It's really easy to learn and has a ton of strong points - security and flexibility being the most important - and really takes your scripts to the next level.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?