【问题标题】:unset array key not working未设置的数组键不起作用
【发布时间】:2014-03-03 21:24:19
【问题描述】:

我正在尝试从表单输入中获取关联数组,这可以正常工作。但是如果数组中已经存在键,我不希望新值重复。这是我的 $_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 ) 
) 

任何帮助将不胜感激。

【问题讨论】:

  • 要么循环引用,要么自下而上取消设置unset(($ls_up_vote[$whatever_the_key_of_arr_is][$key]);

标签: php arrays wordpress unset


【解决方案1】:
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]);
        }
    }
}  

【讨论】:

  • 谢谢。效果很好,但它只删除了键和值。是否可以删除空数组并重新排序数组编号? Array ( [0] =&gt; Array () [1] =&gt; Array ( [user1] =&gt; 44 ) [2] =&gt; Array () [2] =&gt; Array ( [user2] =&gt; 31 ) )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2013-10-18
  • 2014-05-03
相关资源
最近更新 更多