问题描述
我想产生一个多维数组像这样在PHP中:
I'm trying to generate a multidimensional array like this in PHP :
$books = array(
"8" => array( "my girl" => 2.5,
"the god delusion" => 3.5,
"tweak" => 3, "the shack" => 4,
"the birds in my life" => 2.5,
"new moon" => 3.5),
"14" => array( "the last lecture" => 2.5,
"the god delusion" => 3.5,
"the noble wilds" => 3, "the shack" => 3.5,
"the birds in my life" => 2.5, "new moon" => 1)
);
这是这样一个数据库表:
from a database table which is like this :
ID value title
------------------------------------------------------------------
8 5 Clara Callan
8 5 Where You'll Find Me: And Other Stories
8 5 The Middle Stories
8 5 Jane Doe
8 6 The Witchfinder (Amos Walker Mystery Series)
8 6 More Cunning Than Man: A Social History of Rats an...
8 7 Goodbye to the Buttermilk Sky
9 6 Beloved (Plume Contemporary Fiction)
12 10 If I'd Known Then What I Know Now: Why Not Learn f...
14 5 Mary-Kate & Ashley Switching Goals (Mary-Kate ...
14 5 Tell Me This Isn't Happening
14 6 Flood : Mississippi 1927
16 9 Airframe
17 7 Death in the Clouds
17 5 Bant/Spec.Last of the Breed
17 6 Piercing the Darkness
17 3 Prophet
19 7 Prague : A Novel
我已经尝试过多种方法,但我仍然无法弄清楚如何做完全一样的。我一直在寻找多个线程在这里,但仍然没有人这个讨论。我在PHP中的新手,所以我不明白,在PHP太多阵列的概念。目前,我的PHP code是这样的:
I'm already tried several ways but I still can't figure out how to do exactly like that. I've been searching numerous threads in here but still no one discussing about this. I'm a newbie in PHP, so I don't understand too much array concept in PHP. Currently my PHP code is like this :
$result = mysql_query($mySelectQuery) or die("<br/><br/>".mysql_error());
$books = array();
while ($row = mysql_fetch_array($result))
{
$userID = $row{'User-ID'};
$books[$userID] = array($row{'Book-Title'} => $row{'Book-Rating'},);
}
这code已经产生了我想要什么类似的结果,但它仍然是替换现有的书记载,所以最后每个用户只能有一本书记录了数组中为止。我的问题是:
That code already produce similar result with "what I want", but it's still replace the existing book records, so in the end every user only have one book record in their array. My question is:
我怎么能填充格式像我和我的查询结果的多维数组?
How could I populate a multidimensional array formatted like mine with the result of my query?
太感谢了提前为你的答案。很遗憾的英语不好。
Thanks a million in advance for your answers. And sorry for bad English.
推荐答案
尝试:
$result = mysql_query($mySelectQuery) or die("<br/><br/>".mysql_error());
$books = array();
while ($row = mysql_fetch_array($result))
{
$userID = $row{'User-ID'};
$books[$userID][$row{'Book-Title'}] = $row{'Book-Rating'};
}
这将赋予您的书名作为数组键/指数,并设定评价,因为它的价值。
This will assign your book title as a array key/index, and set the rating as it's value.
这篇关于PHP添加数据库结果多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!