jason3w
jason3w

Reputation: 737

Adding values to an array in while loop in PHP from MySQL result

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'];
}

Upvotes: 4

Views: 44754

Answers (2)

user188654
user188654

Reputation:

You simply add a new array as element values for the $menu array.

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

EDIT: How to traverse the array (basically this is PHP 101 so I suggest looking up PHP arrays)

foreach($menu as $index => $record){
    echo "ID: {$record['id']} ParentID: {$record['parentid']} Title: {$record['title']}";
}

Upvotes: 4

Ben
Ben

Reputation: 57209

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.

Upvotes: 25

Related Questions