gpt4 book ai didi

php - 将数据库数据放在多维数组中

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:36 24 4
gpt4 key购买 nike

对于我的网店,我有 1 个数据库和 3 个相关表。为了显示数据,我被建议将这些数据库中的数据放在 3 个二维数组中,这样我就可以直观地看到我在做什么。然而,我将数据放入数组的唯一成功尝试导致代码自身覆盖,只显示表中的最后一个数据。

谁能给我一些关于如何以自动填充的方式设置数组的建议?

<?php
//Create the Multiarrays. 2D, one per table.

// Create connection
$conn = new mysqli(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

//Open the database
$sql = "SELECT * FROM productwindow";
$result = $conn->query($sql);

//Multiarray locatie 1. When the array starts here, the browser chokes.
if ($result->num_rows > 0) {
//multiarray locatie 2. When the array starts here, the browser also chokes.
while($row = $result->fetch_assoc()) {

$product = array( //multiarray locatie 3. The problem is that the array seems to overwrite itself.
array( //I want PHP to repeat this bit of code for every product in my database, so that I can use it later on.
"ID" => $row["ID"],
"Name" => $row["Productname"],
"Price" => $row["Pricetag"],
"Supply" => $row["Productsupply"],
"Tags" => $row["Tags"],
"Materials" => $row["Materials"],
),
);
}
//Multiarray locatie 2 end woul be placed here
} else {
echo "0 results found. Please check database connection.";
}
//Multiarray locatie 1 end woul be placed here.

$conn->close();
//
echo "<br/>";
$searchby = "Pluimstaart";//The keyword that I used in earlier concepts to filter on specific products. I now need a for loop to procedurally run through the multiarray.
$array_subjected_to_search = $product;
$key = array_search($searchby, array_column($array_subjected_to_search, "Name")); //If it cannot be done via a foreloop, I would need an alternative to "array_search" to show the contents of my array.
var_dump($array_subjected_to_search[$key]);//Used to see if I actually fill my array with data. It only shows the latest data.

//From here on out I build the website like follows;
echo "<br/>product data: " . $product[$key["Supply"]] . ".";
?>

非常感谢您的反馈!

最佳答案

$product 变量在每个循环中都被覆盖,因为您每次都使它等于一个全新的数组:

$product = array(...

相反,您应该使用 array_push 将元素追加到数组的末尾。 ,或者这个简写:

$product[] = [
"ID" => $row["ID"],
"Name" => $row["Productname"],
"Price" => $row["Pricetag"],
"Supply" => $row["Productsupply"],
"Tags" => $row["Tags"],
"Materials" => $row["Materials"]
];

关于php - 将数据库数据放在多维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51931007/

24 4 0