我一直在尝试使用mysqli查询创建一个数组,该查询创建了一个新类“Book'”。当我运行此代码时,它返回我在数据库中的正确行数,但它不会显示行中的任何值。绝对是很多这方面的新手,任何帮助都非常感谢!这是我正在运行的代码。如果我只是放入一个预先填充的数组,代码一切都很好。我的问题是将数据库中的值放入此数组中。
$db = new db();
$conn = $db->connect();
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
$thearray = array();
while($array_ar = mysqli_fetch_array($result)){
$thearray[] = array(
$array_ar['username'] => new Book($array_ar['username'], $array_ar['first_name'], $array_ar['last_name']),
);
}
echo 'Rows found: ' . mysqli_num_rows($result);
return $thearray;
好的,所以我var_dump($ thearray);它给了我一个多维数组,这就是它返回空值的原因。我想我需要它来返回一个关联数组?这就是var_dump($ thearray);返回:
array(4) {
[0]=> array(1) {
["joshua"]=> object(Book)#6 (3) {
["title"]=> string(6) "joshua" ["author"]=> string(6) "Joshua" ["description"]=> string(9) "Lundquist"
}
}
[1]=> array(1) {
["matthew"]=> object(Book)#7 (3) {
["title"]=> string(7) "matthew" ["author"]=> string(4) "Matt" ["description"]=> string(3) "Alm"
}
}
[2]=> array(1) {
["roger"]=> object(Book)#8 (3) {
["title"]=> string(5) "roger" ["author"]=> string(5) "Roger" ["description"]=> string(9) "Lundquist"
}
}
[3]=> array(1) {
["norm"]=> object(Book)#9 (3) {
["title"]=> string(4) "norm" ["author"]=> string(4) "Norm" ["description"]=> string(5) "Shupe"
}
}
}
接下来我想我会看看var_dump();对于我的硬编码数组看起来像,它输出这个(这个工作):
array(3) {
["Jungle Book"]=> object(Book)#3 (3) {
["title"]=> string(11) "Jungle Book" ["author"]=> string(10) "R. Kipling" ["description"]=> string(15) "A classic book."
}
["Moonwalker"]=> object(Book)#4 (3) {
["title"]=> string(10) "Moonwalker" ["author"]=> string(9) "J. Walker" ["description"]=> string(7) "another"
}
["PHP for Dummies"]=> object(Book)#5 (3) {
["title"]=> string(15) "PHP for Dummies" ["author"]=> string(14) "Some Smart Guy" ["description"]=> string(18) "and the final one."
}
}
我觉得发生了什么,但我不确定如何修复我的代码。谢谢你的帮助!
答案 0 :(得分:0)
我认为这是问题。
$thearray[] = array(
$array_ar['username'] => new Book(
$array_ar['username'], $array_ar['first_name'], $array_ar['last_name']),
);
看起来你得到的和你想要的东西之间的区别是1)你在$thearray
层中将输入包装到array()
,2)你不会如果您只是使用[]
添加项目,请获取您在硬编码数组中的字符串键。
请尝试这样:
// use the username as a key, since that is what it looks like you're using as the 'title'
$thearray[$array_ar['username']] = new Book(
$array_ar['username'], $array_ar['first_name'], $array_ar['last_name']);
答案 1 :(得分:0)
难道恐慌的回答让我朝着正确的方向前进。我需要创建一个关联数组,而不是一个多维数组。起初我通过将$ thearray设置为“array();”而意外地创建了多维数组。通过删除它,它正确地填充了值。再次感谢您的帮助!
$db = new db();
$conn = $db->connect();
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
$thearray = array();
while($array_ar = mysqli_fetch_array($result)){
$title = $array_ar['username'];
$author = $array_ar['username'];
$description = $array_ar['username'];
$thearray[] = $title = new Book($title, $author, $description);
}
var_dump($thearray);
echo 'Rows found: ' . mysqli_num_rows($result);
return $thearray;