对于一个网店脚本,我试图为我的二维数组创建一个过滤器。 我在Stackoverflow或w3Schools上使用了一些指南和其他答案,但是我一直遇到相同的问题。
新创建的数组只有一个空白,过滤器将在其中提取数据,而不是创建一个0到100个充满相关信息的数组。
由于我仍然对整个多维数组还不熟悉,所以我希望这里的人可以指出正确的方向,并告诉我我做错了什么。
阵列中的数据已完全填满我的数据库
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$product[] = [
"ID" => $row["ID"],
"Name" => $row["Productname"],
"Price" => $row["Pricetag"],
"Supply" => $row["Productsupply"],
"Type" => $row["Producttype"],
"Tags" => $row["Tags"],
"Materials" => $row["Materials"],
"Date" => $row["Releasedate"],
"Description" => $row["Description"],
"isDigital" => $row["isDigital"],
"MainPhoto" => $row["MainPhoto"],
"Photo01" => $row["Productpic01"],
"Photo02" => $row["Productpic02"],
"Photo03" => $row["Productpic03"]
];
}
} else {
echo "0 results found. Please check database connection.";
}
用于过滤此数据并根据键中的匹配项创建新数组的脚本:
$Filterarray = array('Pluimstaart'); //Might filter on more keywords in future usage.
$newArr = array();
foreach ($product as $key => $value) {
foreach ($value as $finalVal) {
if(in_array($finalVal, $Filterarray)){ // check if available in filter array
$newArr[$key]["ID"] = $value["ID"];
$newArr[$key]["Name"] = $value["Name"];
$newArr[$key]["Price"] = $value["Price"];
$newArr[$key]["Supply"] = $value["Supply"];
$newArr[$key]["Type"] = $value["Type"];
//$newArr[$key][] = $finalVal;
}
}
}
网站上的输出:
Array
(
[1] => Array
(
[ID] => 1
[Name] => Pluisje de Pluimstaart
[Price] => 75
[Supply] => 0
[Type] => Pluimstaart
)
[5] => Array
(
[ID] => 69
[Name] => Blizzard de Pluimstaart
[Price] => 75
[Supply] => 1
[Type] => Pluimstaart
)
)
这里的问题是从1跳到5,我希望新数组只说
Array
(
[0] => Array
(
[ID] => 1
[Name] => Pluisje de Pluimstaart
[Price] => 75
[Supply] => 0
[Type] => Pluimstaart
)
[1] => Array
(
[ID] => 69
[Name] => Blizzard de Pluimstaart
[Price] => 75
[Supply] => 1
[Type] => Pluimstaart
)
)
答案 0 :(得分:0)
尝试使用数组函数array_values()
答案 1 :(得分:0)
请像这样使用array_values函数:
$newArr = array(1 => array("one", "two", "three"), 5 => array("horse", "cat", "monkey"));
print_r($newArr); // test print
$newArr = array_values($newArr);
print_r($newArr); // test print
答案 2 :(得分:0)
您要为$ newArr中过滤的每个产品设置一个键,这意味着您将获得具有原始索引的新数组。
为避免这种情况,只需从$ newArr []初始化中删除$ key索引。
$Filterarray = array('Pluimstaart'); //Might filter on more keywords in future usage.
$newArr = array();
foreach ($product as $key => $value) {
foreach ($value as $finalVal) {
if(in_array($finalVal, $Filterarray)){ // check if available in filter array
$newArr[]["ID"] = $value["ID"];
$newArr[]["Name"] = $value["Name"];
$newArr[]["Price"] = $value["Price"];
$newArr[]["Supply"] = $value["Supply"];
$newArr[]["Type"] = $value["Type"];
//$newArr[][] = $finalVal;
}
}
}
或者甚至更好
if(in_array($finalVal, $Filterarray)){
array_push($newArr, array(
"ID" => $value["ID"],
"Name" => $value["Name"],
"Price" => $value["Price"],
"Supply" => $value["Supply"],
"Type" => $value["Type"]
);
}
如果需要跟踪$ key,只需将其存储在其他$ newArr参数中即可。