从 MySQL 结果向 PHP 中的 while 循环中的数组添加值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11462462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding values to an array in while loop in PHP from MySQL result
提问by jason3w
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
抱歉初学者的问题。
我已经搜索了一个小时,只能找到有关在 while 循环中添加 1 个键 => 值的信息。我的目标是这个结果。谢谢
$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'];
}
回答by Ben
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".
关联数组键是使用"key" => "value".
Edit
编辑
Off topic a bit, but I'd stronglyrecommend 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.
有点偏离主题,但我强烈建议您为查询学习 PDO。它真的很容易学习并且有很多优点 - 安全性和灵活性是最重要的 - 并且真正将您的脚本提升到一个新的水平。
回答by brezanac
You simply add a new array as element values for the $menuarray.
您只需添加一个新数组作为数组的元素值$menu。
$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)
编辑:如何遍历数组(基本上这是 PHP 101 所以我建议查找PHP 数组)
foreach($menu as $index => $record){
echo "ID: {$record['id']} ParentID: {$record['parentid']} Title: {$record['title']}";
}

