爆炸并处理php动态数组

时间:2014-02-23 22:27:25

标签: php arrays

我有一个动态构建的表单。 这是表单输入

echo'<input class="input stickyinput" type="number"  name="'.$pestname['scoutlogpestname'].'#'.$obj['card_id'].'" >

$pestname['scoutlogpestname']总是不同的。 $obj['card_id']可以是1-50中的任何值。我把#放在名字中,想要我需要一个分隔符来爆炸。 打印的数组看起来像这样。输入的任何值的数字,未输入的任何值的空白。

Array
(
    [Aphids#1] => 11
    [Thrips#1] => 5
    [White-Fly#1] => 7
    [Aphids#2] => 
    [Thrips#2] => 1
    [White-Fly#2] => 22
    [Aphids#3] => 4
    [Thrips#3] => 1
    [White-Fly#3] => 
    etc....... possibly to 50
)

有人可以给我一些关于如何执行爆炸循环的见解,以便我可以处理$pestname['scoutlogpestname']$obj['card_id']值吗?谢谢你的期待。

3 个答案:

答案 0 :(得分:3)

丢失那个奇怪的哈希事物,只在表单字段中使用数组表示法。例如......

<input name="<?= htmlspecialchars($pestname['scoutlogpestname']) ?>[<?= $obj['card_id'] ?>]" ...

这会产生类似

的东西
<input name="Aphids[1]" ...
<input name="Aphids[2]" ...

提交时,这将为您提供$_POST超级全局数组,例如

Array
(
    [Aphids] => Array
        (
            [1] => 11
            [2] => 
        )
)

然后,您可以迭代每个条目和值数组,例如

foreach ($_POST as $pestname => $values) {
    foreach ($values as $card_id => $value) {
        // code goes here
    }
}

答案 1 :(得分:1)

如果你需要迭代所有字段,那么考虑使用一个简单的foreach并根据“#”拆分数组键:

// e.g. ['Aphids#1' => 11]
foreach ($array as $key => $value) {
    list($pest_name, $card_id) = explode('#', $key, 2);
}

变量$pest_name$card_id根据explode()操作的结果分配了一个值。

另请参阅:list

也就是说,以这种方式将值存储为字段名称的一部分有点笨拙,最好使用像his answer中Phil建议的数组语法。

答案 2 :(得分:0)

另一种方式:

$array = array("Aphids#1" => 11,
    "Thrips#1" => 5,
    "White-Fly#1" => 7,
    "Aphids#2" => 5,
    "Thrips#2" => 1,
    "White-Fly#2" => 22,
    "Aphids#3" => 4,
    "Thrips#3" => 1);

$data = array();
foreach ($array as $key => $value) {
    $exploded = explode('#', $key);
    $obj = array(
        "pest_name" => $exploded[0],
        "card_id"   => $exploded[1],
        "value"     => $value
    );
    array_push($data, $obj);
}

echo "<pre>", print_r($data), "</pre>";

会给你:

Array
(
    [0] => Array
        (
            [pest_name] => Aphids
            [card_id] => 1
            [value] => 11
        )

    [1] => Array
        (
            [pest_name] => Thrips
            [card_id] => 1
            [value] => 5
        )

    [2] => Array
        (
            [pest_name] => White-Fly
            [card_id] => 1
            [value] => 7
        )

    [3] => Array
        (
            [pest_name] => Aphids
            [card_id] => 2
            [value] => 5
        )

    [4] => Array
        (
            [pest_name] => Thrips
            [card_id] => 2
            [value] => 1
        )

    [5] => Array
        (
            [pest_name] => White-Fly
            [card_id] => 2
            [value] => 22
        )

    [6] => Array
        (
            [pest_name] => Aphids
            [card_id] => 3
            [value] => 4
        )

    [7] => Array
        (
            [pest_name] => Thrips
            [card_id] => 3
            [value] => 1
        )

)