可以将子数组作为带有复选框的数组传递给另一个页面吗?

时间:2013-01-04 03:09:59

标签: post multidimensional-array checkbox

我是php的新手,所以请原谅我,如果我问的是基本的问题并且之前会问过。我已经用Google搜索了几天,尤其是这个论坛,我找到了我以前的大部分答案,但我找不到任何问题,所以我必须问。这是我的第一个问题。

// this array is coming from MySQL db as a result. It's a list of user's friends and it could contain dozens or hundreds of friends. Now he wants to put them in different groups.

$array = array(
       array("John", "Doe", "1"),
       array("Peter", "Citizen", "2")
       ...
      );


// a page is created with the result. Each record has a checkbox that the user can select.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

<?php

foreach($array as $item){
$nItem = $item;

?>

<input type="text" name="fname" value="<?php if(isset($nItem)){echo $nItem[0];} ?>" readonly="readonly" />
<input type="text" name="lname" value="<?php if(isset($nItem)){echo $nItem[1];} ?>" readonly="readonly" />
<input type="text" name="uid" value="<?php if(isset($nItem)){echo $nItem[2];} ?>" readonly="readonly" />
<input type="checkbox" name="val[]" value="<?php if(isset($nItem)){echo $nItem;} ?>" /> // I want to send this $nItem array as it is to the action page and read its keys and values there.
<br>

<?php
}
?>

<input type="submit" name="submit" value="Submit">
</form>

<br />

<?php

// if I tick both checkboxes and submit I get the following:

if(isset($_POST['val'])){

$val = $_POST['val'];

echo var_dump($val), '<br />'; // array(2) { [0]=> string(5) "Array" [1]=> string(5) "Array" }

echo count($val), '<br />';    // 2

print_r($val);                 // Array ( [0] => Array [1] => Array )

echo("val is {$val[0]}");      // val is Array

foreach($val as $key => $value){
    echo "Key and Value are: ".$key." ".$value, '<br />'; // Key and Value are: 0 Array
}                                                         // Key and Value are: 1 Array

}

?>

它只返回一个字符串“Array”而不是实际的数组,我可以从中读取velues。如果我将单个值放在复选框值中,例如 -

if(isset($nItem)){echo "".$nItem[0]." ".$nItem[1]." ".$nItem[2]."";}

- 然后我得到了 -

0 John Doe 1

- 但这不是我想要的。我希望我可以迭代的动作页面上的实际数组。我想,因为它已经是一个数组,所以并不困难,但我错了。

有人可以告诉我该怎么做吗?

非常感谢提前。

1 个答案:

答案 0 :(得分:0)

<?php foreach($array as $item): ?>
    <input type="text" name="fname" value="<?php echo $item[0]; ?>" readonly="readonly" />
    <input type="text" name="lname" value="<?php echo $item[1]; ?>" readonly="readonly" />
    <input type="text" name="uid" value="<?php echo $item[2]; ?>" readonly="readonly" />
    <input type="checkbox" name="val" value="<?php echo htmlentities(serialize($item)); ?>" />
    <br>
<?php endforeach; ?>

提交后,反序列化数组$ _POST ['val']。 根据您对此阵列的处理方式,这种方法不仅非常适用于注射。

不是使用包含所有信息的数组,而是最好为每条记录使用id。 名为“val”的复选框具有相应ID的值。

<input type="checkbox" name="val" value="<?php echo $item['id']; ?>" />

提交后,查询属于id的记录并使用返回的数组进行处理。