1

可能重复:
为什么我的 PHP 多维数组不起作用?

更新

我希望能够添加 URL category.php?filter=Blue and green,或者category.php?filter=Red然后让我的数组列表仅显示具有这些值的颜色 - 否则它将列出所有数组。

<?php

$array = array(
"1" => array("red", "black", "blue and green"),
"2" => array("orange"),
"3" => array("silver", "gold"),
"4" => array("pruple"),
"5" => array("pink", "yellow"),
"6" => array("black")
);
# no more more edits, loop begins below
# limit the the rows by 3 and break
$data = array_chunk($array, 3);
/*#######################################
 No more edits DO NOT EDIT FURTHER
#######################################*/?>
<?php
foreach ($array as $data):
?>

<div class="item" id="item_<?= $row ?>">
    <div class="itemdata">
    <?php #foreach ($array as $row): ?>
    <?php foreach ($data as $row): ?>
        <?php if (in_array($row, explode(' and ', $_GET['filter']))): ?>
            Product Link = <?=$row?> 
        <?php endif; ?>
    <?php endforeach ?>
    </div>
</div>
<?php endforeach ?>

我已经根据下面的帖子更新了我的代码。到目前为止,它只循环了两个项目 - 没有filter应用于 URL

4

4 回答 4

3

首先,您的数组似乎不正确:

# list of product Ids and their assoc colours
$array = array(
"1" => "red", "black", "blue and green",
"2" => "orange",
"3" => "silver", "gold",
"4" => "pruple",
"5" => "pink", "yellow",
"6" => "black"
);

如果产品 1 有 3 种颜色,它可能应该是:

array (
    1 => array("red", "black", "blue"),
    2 => array("orange"),

等等

于 2012-10-01T09:54:11.110 回答
1

我修复了数组和循环,并添加了一个过滤器:

http://codepad.org/YnafFVP4

array_chunk打破你的多维数组,所以你不能使用它。如果您可以解释您想要限制的内容,我们也可以提供帮助。

于 2012-10-01T10:06:04.907 回答
0

首先,您的数组不正确。它必须像:

$array = array ("1" => array("red", "black", "blue"),
    //etc
)

其次,您的 foreach 似乎不正确。

Foreach 看起来像:

foreach($array as $key => $value)

或者

foreach($array as $value)

这将导致我们如下:

<?php foreach ($array as $data): ?>
    // ...
    <?php foreach ($data as $row): ?>
        <a href="/products/<?=$row?>"><img src="/products/<?=$row?>.jpg" /></a>
    <?php endforeach ?>
    //...
<?php endforeach ?>

你要回答你的第二个问题:

在 PHP 中,如果添加[]到变量名中,则可以在 url 中传递数组:

/?color[]=blue&color[]=green

并得到它$_GET['color[]'];

作为一般提示:使用{}块而不是:and endforeach。这样你也可以做 IF ELSE 构造:

<?php
    if($a == $b) {

    } else {

    }
?>
于 2012-10-01T10:04:22.110 回答
0

这就是你的数组应该是什么样子

$array = array(
"1" => array("red", "black", "blue and green"),
"2" => "orange",
"3" =>  array("silver", "gold"),
"4" => "pruple",
"5" => " array(pink", "yellow"),
"6" => "black"
);
于 2012-10-01T09:57:27.847 回答