我的多维数组正在运行。但是,在通过explode
in_array
或$_GET
来限制数组
<?
$shop = array(
array("red", "black", "blue", "green"),
array("orange"),
array("orange", "black"),
array("pink", "yellow")
);
foreach ($shop as $rowNumber => $row)
{
echo "<li><b>The row number $rowNumber</b>";
echo "<ul>";
foreach ($row as $col) {
if (in_array($col, explode(' and ', $_GET['filter']))){
echo "<li>".$col."</li>";
}
}
echo "</ul>";
echo "</li>";
}
?>
如果我用$_GET["filter"]=="black"
运行脚本,它会显示所有项目 - 它应该只显示两个,例如这是错误的:其他行不应出现:
应该是这个
答案 0 :(得分:2)
解决方案1
<?
$shop = array(
array("1", "red", "black", "blue and green"),
array("2", "orange"),
array("3", "pink", "yellow", "blue and green")
);
for ($row = 0; $row < count($shop); $row++)
{
$lis = "";
for ($col = 0; $col < count($shop[$row]); $col++)
{
if (in_array($shop[$row][$col], explode(' and ', $_GET['filter']))
|| empty($_GET['filter'])){
$lis .= "<li>".$col."</li>";
}
}
if($lis != "") {
echo "<li><b>The row number $row</b>";
echo "<ul>";
echo $lis;
echo "</ul>";
echo "</li>";
}
}
?>
解决方案2
<?
$shop = array(
array("1", "red", "black", "blue and green"),
array("2", "orange"),
array("3", "pink", "yellow", "blue and green")
);
for ($row = 0; $row < count($shop); $row++)
{
$lis = "";
for ($col = 0; $col < count($shop[$row]); $col++)
{
if (in_array($shop[$row][$col], explode(' and ', $_GET['filter']))){
$lis .= "<li>".$col."</li>";
}
}
if($lis=="") {
echo "$row";
} else {
echo $lis;
}
}
?>
答案 1 :(得分:0)
你的col-Variable包含一个数字(1,2或3)但是explode-call返回一个包含单词的数组(绿色,蓝色,橙色)
即使PHP可以处理从1到“1”的强制转换,它也不能从1转换为“绿色”。
答案 2 :(得分:0)
Just Gussing也许你想打印像这样的东西
$shop = array(array("1","red","black","blue and green"),array("2","orange"),array("3","pink","yellow","blue and green"));
echo "<ul>";
foreach ( $shop as $info ) {
$info = array_pad($info, 4, "none");
list($id, $color1, $color2, $mixed) = $info;
printf("<li><b>The row number = %d , Color = 1 %s , Color 2 = %s , Mixed = %s </b></li>", $id, $color1, $color2, $mixed);
}
echo "</ul>";
输出
答案 3 :(得分:0)
我认为你可以做这样的事情:
<?
$shop = array(
array("red", "black", "blue", "green"),
array("orange"),
array("orange", "black"),
array("pink", "yellow")
);
foreach ($shop as $rowNumber => $row)
{
echo "<li><b>The row number $rowNumber</b>";
echo "<ul>";
foreach ($row as $col)
{
//Compare both values, if they match, it prints
if ($col == $_GET['filter'])
{
echo "<li>".$col."</li>";
}
}
echo "</ul>";
echo "</li>";
}
?>