下面是我的数组的一个示例。我试图计数每次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
)
)
这是可能的吗?
让您的示例输入为下面代码中的$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 );
}
如果您对关联数组满意,则可以删除第二个循环。