首页 > 解决方案 > 在 PHP 中提交表单后匹​​配表单发布数组值

问题描述

我有一个表格:

<form action="index.php" method="post">

具有多个选择输入

<select class="form-control" id="location" name="location[]" >
<option selected disabled value="">Choose Location</option>
<option value="closing">Closing Station</option>
<option value="device">Device/ROF</option>
<option value="merch1">General Merch 1</option>
<option value="merch2">General Merch 2</option>
</select>
<input type="hidden" name="image_name[]" value="<?php echo $file; ?>" />

我在提交表单时有这个数组:

Array (
    [location] => Array (
    [0] => closing 
    [1] => merch1 
    [2] => merch2 ) 

    [image] => Array ( 
    [0] => AL-AL.jpg 
    [1] => AL-AN.jpg 
    [2] => AL-AV.jpg 
    [3] => AL-CA.jpg 
    [4] => AL-CL.jpg 
    [5] => AL-CM.jpg ) 

    [submit] => Submit 
)

我希望 PHP 中的输出是这样的:位置 [0] 和图像 [0] 等:这是我的代码:

<?php
            if (isset($_POST['submit'])){
                 foreach ($_POST['location'] as $location) {
                foreach ($_POST['image_name'] as $image) {
    echo "you have selected $image to go to this location: $location <br/>";
                            }
                        }
                    }
            }
?>  

目前正在输出:

you have selected AL-AL.jpg to go to this location: closing 
you have selected AL-AN.jpg to go to this location: closing 
you have selected AL-AV.jpg to go to this location: closing 
you have selected AL-CA.jpg to go to this location: closing 
you have selected AL-CL.jpg to go to this location: closing 
you have selected AL-CM.jpg to go to this location: closing 
you have selected AL-AL.jpg to go to this location: merch2 
you have selected AL-AN.jpg to go to this location: merch2 
you have selected AL-AV.jpg to go to this location: merch2 
you have selected AL-CA.jpg to go to this location: merch2 
you have selected AL-CL.jpg to go to this location: merch2 
you have selected AL-CM.jpg to go to this location: merch2 

它现在似乎是一个永恒的循环。我知道有一种方法可以匹配 [] 值上的每个数组,然后仅在匹配的地方输出,但我无法弄清楚。

标签: phparraysforms

解决方案


不需要 2 个循环,使用来自位置的键来查找图像

<?php
$p['location'][0]='closing'; 
$p['location'][1]='merch1';
$p['location'][2]='merch2'; 

$p['image'][0]='AL-AL.jpg'; 
$p['image'][1]='AL-AN.jpg'; 
$p['image'][2]= 'AL-AV.jpg'; 

foreach($p['location'] as $k=>$v ){
echo "you have selected ".$p['image'][$k]." to go to this location: $v <br/>";
}

?>

输出:

您已选择 AL-AL.jpg 前往此位置:关闭
您已选择 AL-AN.jpg 前往此位置:merch1
您已选择 AL-AV.jpg 前往此位置:merch2


推荐阅读