【问题标题】:PHP array failing to POST with other form dataPHP 数组无法与其他表单数据一起发布
【发布时间】:2015-01-15 10:43:15
【问题描述】:

我有一个名为 $content_ids 的数组,我试图将其作为隐藏字段发布到表单中。

我在这里的另一个答案中找到了如何做到这一点,但我无法让它工作。

这只是我的一些输入,包括数组的隐藏字段

echo "<input type=\"hidden\" value=\"1\" name=\"e\">";
foreach($content_ids as $ids)
{
    echo "<input type=\"hidden\" value=\"".$ids."\" name=\"ids[]\">";
}
echo "<input type=\"hidden\" value=\"".$content[$x]['TranslationID']."\" name=\"translationID\">";

尝试 print_r($_POST['ids']) 什么也没显示

试试这个:

if($_POST['ids'] != ""){
    echo "hello";
}

也没有给出任何东西。但是其余的数据都通过了。

有人知道为什么吗?

编辑添加:经过测试以确保数组在将数据放入隐藏字段时实际包含数据。在设置隐藏字段之前立即打印出数组并且所有显示都正常。

编辑添加:数组是如何制作的:

$content_ids = array();
    for($i = 0; $i < count($content); $i++)
    {
        $content_ids[] = array_push($content_ids, $content[$i]['ContentID']);   
    }

数组的输出是:

数组([0] => 2222 [1] => 1 [2] => 1111 [3] => 3)

我其实不知道为什么会有索引 1 或索引 3。它们不是数据库数据的一部分。它应该只包含 1111 和 2222。

【问题讨论】:

  • 你试过if(!empty)而不是!= ""吗?
  • 使用 'var_dump($_POST[]);' 检查帖子,看看里面是否有数据。
  • 使用 var_dump 显示除我需要的数组之外的所有值
  • 你能显示数组$content_ids的值吗?

标签: php arrays forms post hidden


【解决方案1】:

我已运行此代码并能够获取所有发布的值

   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    </head>
    <body>
    <form action ="" method="POST" >
    <?php 
    //supose your values are 
    $content_ids = array('10','20');
    $x = 1;
    $content[$x]['TranslationID'] =20;
    // your code
    echo "<input type=\"hidden\" value=\"1\" name=\"e\">";
    foreach($content_ids as $ids)
    {
        echo "<input type=\"hidden\" value=\"".$ids."\" name=\"ids[]\">";
    }
    echo "<input type=\"hidden\" value=\"".$content[$x]['TranslationID']."\" name=\"translationID\">";

    ?>
    <input type="submit" />
    </form>
    </body>
    </html>
    <?php print_r($_POST); ?>

这里是输出

Array ( [e] => 1 [ids] => Array ( [0] => 10 [1] => 20 ) [translationID] => 20 ) 

【讨论】:

  • 您的代码确实按预期工作,但我的仍然没有。我的数组“$content_ids”是根据数据库查询的结果创建的。我只是在看那个,看看我是否做错了。尽管数组填充了正确的结果
  • 你能用
  • 在数组变量中赋值之前检查值是否为空 if(trim($content[$i]['ContentID']) !='' ){ $content_ids[] = array_push($content_ids , $content[$i]['ContentID']); }
【解决方案2】:

我发现了问题。我认为问题出在数组的创建上。

我唯一改变的是:

$content_ids = array();
    for($i = 0; $i < count($content); $i++)
    {
        $content_ids[] = array_push($content_ids, $content[$i]['ContentID']);   
    }

我把它改成了这样:

$content_ids = array();
    for($i = 0; $i < count($content); $i++)
    {
        array_push($content_ids, $content[$i]['ContentID']);    
    }

我不知道怎么做,但这似乎修复了数组中不需要的索引以及无法作为隐藏字段发布的问题。

我现在成功地将数组作为 POST 变量。谢谢大家的帮助

【讨论】:

  • 你也可以使用 array_values() 从数组中删除键
  • 如果我没记错的话,你可以完全避免array_push,直接使用$some_array[]=$some_value。我可能是错的,但我记得在某处读过它实际上是有效的(无论如何这并不重要,因为这些级别的性能应该没有那么重要 - 当然,除非你的代码在它上面花费了太多时间)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 2016-05-06
  • 2017-03-19
相关资源
最近更新 更多