簡體   English   中英

未設置數組鍵不起作用

[英]unset array key not working

我正在嘗試從表單輸入中獲取關聯請求,但效果很好。 但我不希望新值重復,如果鍵已經存在於數組中。 這是我的$ _POST函數的外觀:

<?php // top of page
if ( isset( $_POST['drw_inventory'] ) && wp_verify_nonce($_POST['drw_inventory'],'update_drw_postmeta') )
{
      //if nonce check succeeds.
      global $post;
      $postid = $post->ID;
      $data = $_POST['wpd_function_rating'];
      $currentusr = wp_get_current_user();

      //Get the Existing user ratings of this post
      $ls_up_votes = (get_post_meta($postid, 'wpd_rating', TRUE ));

      //if the current user already rated, unset the rating
      foreach($ls_up_votes as $arr) {
          foreach($arr as $key => $value) {
              if (array_key_exists($currentusr->user_login, $arr)) {
                    unset($arr[$key]);
               }
          }
      }   
      //Add post meta 'wpd_rating' with this structure: 
      $ls_up_votes[] = array($currentusr->user_login => $data);
      update_post_meta($postid,'wpd_rating',$ls_up_votes);  
}
?>

表格

<form method="post" action="">
   <?php wp_nonce_field('update_drw_postmeta','drw_inventory'); ?>
   <label>This is label</label>
   <input type='text' name='wpd_function_rating' value='' />
   <input type='submit' value='save' />
</form>

這是我的數組的外觀(您可以看到重復的用戶輸入,我希望在現有的用戶名鍵上更新數組的值):

Array ( 
[0] => Array ( [user1] => 33 ) 
[1] => Array ( [user1] => 44 ) 
[2] => Array ( [user2] => 34 ) 
[2] => Array ( [user2] => 31 ) 
) 

任何幫助,將不勝感激。

foreach ( $ls_up_votes as $k => $v ) {
    foreach ( $v as $k2 => $v2 ) {
        if ( array_key_exists($currentusr->user_login, $v) ) {
            unset($ls_up_votes[$k][$k2]);
        }
    }
}  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM