【问题标题】:Update a value of a specific key of an associative array更新关联数组的特定键的值
【发布时间】:2014-03-23 12:05:09
【问题描述】:

我正在尝试使用表单更新关联数组的特定键的值。

这是我的表单的外观:

<form class="wpd_edit_note_322" method="post" action="">
<input type="hidden" id="list_note" name="list_note" value="ba222f06db">
<p><textarea id="plugn_note" name="plugin_note" placeholder="Note(Optional)" ></textarea></p>
<p><input class="list_note_id" name="plugin_note_id" type="hidden" value="322"></p>
<p><input class="list_edit_button" type="submit" value="Save"></p>

</form>

这就是我在提交时尝试更新键 322 的值的方式:

    if ( isset( $_POST['list_note'] ) && wp_verify_nonce($_POST['list_note'],'edit_item_note') )
    { 


        $add_to_ID = $_POST['plugin_note_id'];
        $note = $_POST['plugin_note'];


        $existing_list = Array ( 
    [0] => Array ( [320] => This is the plugin that I am using on my site. ) 
    [1] => Array ( [322] => My Microblog poster bla blah bla. ) 
    [2] => Array ( [318] => ) 
    );
foreach ( $existing_list as $k => $v ) {
      $existing_list[$k][$add_to_ID] = $note;
        } 
}

当我回显它时,我看到了 $_POST 值。所以我猜这个表单可以正常工作,但是 foreach 循环不能正常工作。

我还尝试使用 array_walk_recursive() 代替 foreach 循环,此处提到但无济于事: How to change the value of an specific associative array in PHP?

有人可以帮帮我吗?

谢谢

【问题讨论】:

  • $existing_list 的数组语法不正确。这是您的实际代码吗?
  • $existing_list 数组中的每一行后都需要逗号
  • 数组列表实际上是print_r 版本的get_post_meta($postid, 'my_list_items', TRUE ) 我刚刚添加了打印版本来显示数组。我应该使用var_dump 输出吗?谢谢。

标签: php arrays


【解决方案1】:

您的代码实际上将数组($add_to_ID => $note) 添加到 $existing_list 数组的每个元素中,但它会更改索引为 322 的元素。尝试以下操作:

foreach ($existing_list as $key => $value) {
    if (isset($value[$add_to_ID])) {
        $existing_list[$key][$add_to_ID] = $note;
        break;
    }    
}

【讨论】:

  • var_dump($existing_list) 的输出是什么?将其放在 foreach 之后,但不在 `if ( isset( $_POST['list_note'] ) ...' 块之外。
  • 如果我在if 中添加代码,但如果我在foreach 循环中添加代码,我什么也得不到。我明白了:array(3) { [0]=&gt; array(1) { [320]=&gt; string(46) "This is the plugin that I am using on my site." } [1]=&gt; array(1) { [322]=&gt; string(59) "My Microblog poster blah bla bla" } [2]=&gt; array(1) { [318]=&gt; string(0) "" } } 谢谢。
  • 您是否将 var_dump 放在了 foreach 内的 if 块中?如果是,则意味着条件永远不会为真。转储 $add_to_ID 和 $note 的值。输出是什么?
  • 我在break; 之后添加了var_dump($add_to_ID); var_dump($note);,但没有得到任何输出。但是当我在break; } 之后添加代码时,我得到表单提交值作为输出。
  • break 之后它将不起作用。但似乎 isset 条件永远不会为真,所以我建议再次检查所有值(数组、数组键、发布数据)。代码似乎没问题,值有问题。
猜你喜欢
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 2019-11-30
  • 2017-09-01
  • 2021-03-16
相关资源
最近更新 更多