Reputation: 425
I am trying to update a value of a specific key of an associative array with a form.
This is how my form looks:
<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>
and this is how I am trying to update the value of key 322
on submit:
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;
}
}
I see the $_POST values when I echo it out. so I guess the form is working but the foreach loop is not working properly.
I also tried to use array_walk_recursive()
instead of the foreach loop, mentioned here with no avail:
How to change the value of an specific associative array in PHP?
Can someone help me out?
Thanks
Upvotes: 0
Views: 957
Reputation: 442
Your code actually adds the array($add_to_ID => $note) to every element of the $existing_list array, but it changes the one with the index 322. Try something like this:
foreach ($existing_list as $key => $value) {
if (isset($value[$add_to_ID])) {
$existing_list[$key][$add_to_ID] = $note;
break;
}
}
Upvotes: 1