【问题标题】:unable to count past the first arrays values when trying to count multiple arrays尝试计算多个数组时无法计算超过第一个数组的值
【发布时间】:2017-08-16 03:08:44
【问题描述】:

以下发生在 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。

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

【问题讨论】:

  • 您需要实际拆分字符串。试试 $array = explode(",", $user->followers);

标签: php arrays wordpress foreach counting


【解决方案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
)

【讨论】:

  • 好的,谢谢,看起来很有效。现在我得到“11”的结果,我猜它在 1 个数组中找到 1 个结果,在第二个数组中找到第二个 1 结果,我猜这是正确的。那么现在我如何将两个 1 相加得到 2?
  • 这很容易。这样做:$counts= array_count_values ($array ); 然后 $count 将有一个数组,其中值作为索引,其计数作为值。签出:php.net/manual/en/function.array-count-values.php
猜你喜欢
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多