通过匹配从html页面传递的值来创建新数组

时间:2014-08-15 13:01:37

标签: php html arrays post

编辑:

这就是我想要实现的目标:

HTML页面通过POST方法传递多个字符。 php抓住它,现在 根据从HTML页面传递的值,我想通过匹配php中已存在的数组项来创建一个新数组。

例如: HTML将这些值传递给php $_POST['a1'] | $_POST['a2'] | $_POST['a5'] | $_POST['a8']

这是php中的固定项数组。 $fixedItems = array(chair, cup, ladder, bed, pillow, shoes, apple, sprrrow);

如何通过将HTML传递的项与$fixedItems数组进行匹配来创建NEW数组。

if `$_POST['a1']` add "chair" to $fixedItems
if `$_POST['a2']` add "cup" to $fixedItems
if `$_POST['a3']` add "ladder" to $fixedItems 
if `$_POST['a4']` add "bed" to $fixedItems 
if `$_POST['a5']` add "pillow" to $fixedItems 

等......

上述示例的最终结果应为:

$fixedItems = array("chair", "cup", "pillow");

5 个答案:

答案 0 :(得分:2)

我没有完全理解你在说什么,但你可以在php中使用array_push()函数将数据插入数组中。使用下面的代码

<?php
$fixedItems = array();
if (isset($_POST['a1'])){ array_push($fixedItems, "Chair");}
if (isset($_POST['a2'])){ array_push($fixedItems, "Cup"); }
if (isset($_POST['a3'])){ array_push($fixedItems, "Ladder"); }
if (isset($_POST['a4'])){ array_push($fixedItems, "bed"); }
if (isset($_POST['a5'])){ array_push($fixedItems, "Pillow"); }
?>

我希望这有助于你

答案 1 :(得分:1)

最简单的方法是稍微更改一下$fixedItems数组:

$fixedItems = array(
    'a1' => 'chair',
    'a2' => 'cup',
    'a3' => 'ladder',
    'a4' => 'bed',
    'a5' => 'pillow',
    'a6' => 'shoes',
    'a7' => 'apple',
    'a8' => 'sprrrow',
);

$freshArray = array();
foreach ($fixedItems as $key => $value) {
    if (isset($_POST[$key])) $freshArray[] = $value;
}

根据您的需要,您需要使用上面的empty

如果您将来需要更多发布的元素,上面的代码最容易扩展,因为您只需将另一个项目添加到数组中它就会自动生效。

演示:https://eval.in/179698

答案 2 :(得分:0)

你在找这样的东西吗?

// Create the array that will hold the matched data 
$newArray = array();
// Here are your matching conditions
$fixedItems = array('chair', 'cup', 'ladder', 'bed', 'pillow', 'shoes', 'apple', 'sprrrow');
// Loop through the info sent from the front-end
foreach($_POST AS $k => $v){
    // Check if the item posted is in the matching array
    if(in_array($k, $fixedItems)){
        // Add them to your new array, to build up your custom array of matched conditions.
        array_push($newArray, $v);
    }
}

答案 3 :(得分:-1)

我的理解是你想构建$ fixedItems数组,具体取决于所设置的POST字段。

实现这一目标的方法是array_push(); php的功能

示例:

//Empty Array    
$fixedItems = array();

//Your if statement
if (isset($_POST['a1'])){
//Add it to the array
  array_push($fixedItems, "Chair");
}

答案 4 :(得分:-2)

您可以尝试使用foreach自动创建数组

  if (!empty( $_POST))
        {
            foreach ($_POST as $key => $value)
            {
                $fixedItems = array_push($fixedItems, $_POST[$value]);
            }

        }
  return $fixedItems;