1

The following takes place in 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];
    }

}

the result is that i get a value of "1" but it should be "2" since the author_id in this example is 2 and there are 2 strings that contain 2 in them.

i feel like its only checking for the author_id in the first array in the series of arrays.

can you help me figure out what im doing wrong?

1
  • 1
    You need to actually split the string. Try $array = explode(",", $user->followers); Commented Aug 16, 2017 at 3:12

1 Answer 1

1

Change this line

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

to

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

Because say you have $followers ="3,4,5,1"; Then:

$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
)
Sign up to request clarification or add additional context in comments.

2 Comments

ok cool thanks that looks like it works. now i get a results of '11' which i guess is that it found 1 result in 1 array and a second 1 result in a second array, which i guess is correct. so now how do i add the two 1's together to get 2?
Thats easy. Do this: $counts= array_count_values ($array ); Then $count will have an array with the values as index and its count as values. Check out: php.net/manual/en/function.array-count-values.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.