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


Create new array by matching values passed from html page

EDIT:

这就是我想要达到的目标:

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数组传递的项目来创建新的数组。

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");

我不完全明白你在说什么,但是你可以使用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"); }
?>

希望这对你有帮助

最简单的方法是稍微改变您的$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

如果你将来需要更多的post元素,上面的代码使你的代码最容易扩展,因为你可以简单地向数组中添加另一项,它就会自动工作。

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

你在找这样的东西吗?

// 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);
    }
}

我的理解是,您希望根据设置的POST字段来构建$fixedItems数组。

一种实现方法是array_push();php的函数

例子:

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

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

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