更新foreach循环中的多维数组

时间:2015-11-24 12:17:38

标签: php arrays multidimensional-array foreach

我有多维数组,我在foreach循环中回显了键和值。我想在'id'(键)旁边有一个更新框来更新id值,并在'size'(键)旁边更新大小值

问题 :: 贝娄是我的代码,输入框回显每个键的正确值,但当我点击更新按钮时,它会更新...

更新不必在foreach循环中,顺便说一下。我只是觉得它会更容易

提前致谢所有帮助

代码

        <?php
session_start();

 $array=array(
'Homer' => Array
(
    'id' => 111,
    'size' => 54

),
  'Marge' => Array
(
    'id' => 222,
    'size' => 12

),
'Bart' => Array
(
    'id' => 333,
    'size' => 3
)
);
// update if submit
if (isset($_POST["submit"])) 
{
    // i tired a number of things here but it was all errors 

}
echo "<form method='post' action=''>";

// put the array in a session variable
if(!isset($_SESSION['simpsons']))
$_SESSION['simpsons']=$array;


// getting each array in a foreach loop         
foreach( $_SESSION['simpsons'] as $character => $info) { 

        echo $character.': id is '.$info['id'].', size is '.$info['size'];
        //add and update input box for each ' id '      and    '  size '


?>

<!-- input for id -->
<input name="<?php $character ?>" value="<?php echo $info['id'] ?>">
<!-- input for size-->
<input name="<?php $character ?>" value="<?php echo $info['size'] ?>">

<?php

echo"<br/>"; 
}

?>

<!-- submit button for the form -->
<input class="inputbox" type="submit" value="Update value of key" name="submit"/>
</form>

2 个答案:

答案 0 :(得分:-1)

您有两个具有相同名称的输入(两次<input name="Homer" ...>)。我建议使用通用解决方案:

<input type="text" name="names[]" value="<?php echo $character;?>" />
<input type="text" name="ids[]" value="<?php echo $info['id'];?>" />
<input type="text" name="sizes[]" value="<?php echo $info['size'];?> />

然后你会在你的PHP代码中通过帖子接收数据(如果你不想把这个名字看作输入字段,那就把它变成type="hidden")。

<?php
$names = $_POST['names'];
$ids = $_POST['ids'];
$sizes = $_POST['sizes'];
foreach ($names as $key=>$value) {
    //name is $value
    //id is $ids[$key]
    //size is $sizes[$key]
}

答案 1 :(得分:-1)

foreach应该是

    foreach( $_SESSION['simpsons'] as $tt2) {
       print_r($tt2);
        foreach($tt2 as $character => $info){

       echo $character.': id is '.$info['id'].', size is '.$info['size'];
       //add and update input box for each ' id '      and    '  size '
      }
   }