代码之家  ›  专栏  ›  技术社区  ›  Ugh

尝试计数多个数组时,无法计数超过第一个数组的值

  •  1
  • Ugh  · 技术社区  · 7 年前

    以下内容发生在WordPress中。。

    // get the current page author
    
    $curauth    = (isset($_GET['author_name'])) ? get_user_by('slug', 
    $author_name) : get_userdata(intval($author));
    
    // get the current page authors id (in this case its 2)
    
    $author_id  = $curauth->ID;
    
    // set the $args to get the value of the users meta_key named 'followers'
    
    $args = array(
        'meta_key'     => 'followers',
    );
    
    // setup the get_users() query to use the $args
    
    $users  = get_users($args);
    
    // setup a foreach loop to loop through all the users we just queried getting the value of each users 'followers' field
    
    foreach ($users as $user) {
    
    // $user->folllowers returns:
    // 2
    // 1,3,5
    // 3,4,5
    // 3,5,1,4
    // 3,4,5,1
    // 1,2
    // which is a series of comma separated strings.
    // so then i turn each string into an array:
    
        $array = array($user->followers);
    
        // go through each array and count the items that contain the authors id
    
        for($i = 0; $i < count($array); $i++) {
            $counts = array_count_values($array);
            echo $counts[$author_id];
        }
    
    }
    

    你能帮我找出我做错了什么吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Amit Joshi    7 年前

    更改此行

     $array = array($user->followers);
    

     $array = explode(",", $user->followers);
    

    因为说你有 $followers ="3,4,5,1"; 然后:

    $array = array($followers); 
    print_r($array);
    
    Output:
    Array
    (
        [0] => 3,4,5,1
    )
    
    
    $array = explode(",", $followers);  
    print_r($array);
    
    Output:
    Array
    (
        [0] => 3
        [1] => 4
        [2] => 5
        [3] => 1
    )