2017-08-16 63 views
1

以下时计数过去的第一阵列值发生在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”的值,但它应该是“2 “因为这个例子中的author_id是2,并且有2个字符串包含2个字符串。

我觉得它只是在数组序列的第一个数组中检查author_id。

你能帮我弄清楚我做错了什么吗?

+1

实际上你需要拆分字符串。尝试$ array = explode(“,”,$ user-> followers); – ishegg

回答

1

改变这一行

$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 
) 
+0

好酷感谢,看起来像它的作品。现在我得到'11'的结果,我猜测它发现1个结果在1个数组中,第二个1结果在第二个数组中,我猜测是正确的。所以现在我怎么把两个1加在一起得到2呢? – Ugh

+0

这很容易。做到这一点:'$ counts = array_count_values($ array);'然后$ count将有一个数组作为索引和它的数值作为值。检查:http://php.net/manual/en/function.array-count-values.php –