0

下面是我的数组示例。每次 user_id 在数组中时,我都会尝试计算。每次 user_id 在数组中时,我都会尝试计算。

Array
(
[0] => Array
    (
        [user_id] => 57002892
        [page_id] => 109446562415595
    )

[1] => Array
    (
        [user_id] => 515576073
        [page_id] => 109446562415595
    )

[2] => Array
    (
        [user_id] => 560299932
        [page_id] => 109446562415595
    )

[3] => Array
    (
        [user_id] => 607960053
        [page_id] => 109446562415595
    )

[4] => Array
    (
        [user_id] => 607960053
        [page_id] => 109446562415595
    )
)

这应该输出以下内容:

Array
(
[0] => Array
    (
        [user_id] => 57002892
        [count] => 1
    )

[1] => Array
    (
        [user_id] => 515576073
        [count] => 1
    )

[2] => Array
    (
        [user_id] => 560299932
        [count] => 1
    )

[3] => Array
    (
        [user_id] => 607960053
        [count] => 2
    )
)

这可能吗?

4

1 回答 1

0

在下面的代码中,让您的示例输入为 $input_array:

$user_id_hash = array();
foreach( $input_array as $occur )
{
    if( !array_key_exists( $occur['user_id'], $user_id_hash ) )
    {
        $user_id_hash[$occur['user_id']] = 0;
    }
    $user_id_hash[$occur['user_id']]++;
}
$user_id_arr = array();
foreach( $user_id_hash as $user_id => $count )
{
    $user_id_arr[] = array( 'user_id' => $user_id, 'count' => $count );
}

如果你对关联数组没问题,你可以放弃第二个循环。

于 2013-03-11T03:50:29.640 回答