0

I am trying to change the value of a specific key of an associative array which was saved in my post meta. This is how my array is saved in a custom field:

Array ( 
    [0] => Array (
        [321] => Zedity is an innovative content Editor to create posts or pages
    )
    [1] => Array (
        [310] => A shortcode that includes other posts
    )
)

This is how I am trying to update the value of key 321:

global $post;
$postid = $post->ID;
$add_to_ID = $_POST['wpd_plugin_note_id'];
$note = $_POST['wpd_plugin_note'];

$existing_list = get_post_meta($postid, 'my_list_items', TRUE );

foreach ($existing_list as $key => $value) {
    $existing_list[$key][$add_to_ID] = $note;
}    
update_post_meta($postid,'my_list_items',$existing_list);

It works, but after the update the array looks like this, instead of updating the value of key 321, the key=value pair is being added 2 times:

Array ( 
    [0] => Array (
        [321] => my new value for 321
    ) 
    [1] => Array (
        [310] => A shortcode that includes other posts
        [321] => my new value for 321
    )
)

Can anyone tell me what I am doing wrong? Thanks

1

This is plain PHP (logic):

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

What you did before was not update the sub-element with key 321 for each element but set the sub-element with that particular key for each element—which is in essence: update where already defined, define otherwise.

  • 1
    thanks so much. I forgot to mention I am pretty new to php :) – Towfiq Feb 22 '14 at 7:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.