I'm trying to loop through all the pages of a determined forum thread and get the total number of posts by each user but I'm struggling to understand how to sum each time the username is repeated inside the array.
Here's my code:
for ($x = 1; $x <= 5; $x++) {
$ch = curl_init('http://myforum.com/thread-123?&page=' . $x);
curl_setopt_array($ch, array(
CURLOPT_HEADER => TRUE,
CURLOPT_RETURNTRANSFER => TRUE
));
$response = curl_exec($ch);
preg_match_all('/me\">[\s]+<a href=\"([^\"]+)\">([^<]+)/i', $response, $users);
preg_match_all('/image_avatar\" src=\"([^\"]+)"/i', $response, $avatar);
$q = count($users[1]);
for ($i = 0; $i < $q; $i++) {
///////count how many times the user was inside the array///////
//$totalPosts = ?
///////count how many times the user was inside the array///////
print '-----<br /><img src="'.$avatar[1][$i].'" /><br />User: ' . $users[2][$i] . '<br />Total Posts: ' . $totalPosts . '-----<br />';
}
}
Solution, thanks @u_mulder
$all_users = array();
for ($x = 1; $x <= 5; $x++) {
$ch = curl_init('http://myforum.com/thread-123?&page=' . $x);
curl_setopt_array($ch, array(
CURLOPT_HEADER => TRUE,
CURLOPT_RETURNTRANSFER => TRUE
));
$response = curl_exec($ch);
preg_match_all('/me\">[\s]+<a href=\"([^\"]+)\">([^<]+)/i', $response, $users);
preg_match_all('/image_avatar\" src=\"([^\"]+)"/i', $response, $avatar);
$all_users = array_merge($all_users, $users[2]);
}
function aprint($arr, $return = false) {
arsort($arr);
$wrap = '<div style=" white-space:pre; position:absolute; top:10px; left:10px; height:200px; width:100px; overflow:auto; z-index:5000;">';
$wrap = '<pre>';
$txt = preg_replace('/(\[.+\])\s+=>\s+Array\s+\(/msiU','$1 => Array (', print_r($arr,true));
if ($return) return $wrap.$txt.'</pre>';
else echo $wrap.$txt.'</pre>';
}
$res = array_icount_values ($all_users);
$res2 = aprint($res);
print_r($res2);
function array_icount_values($arr,$lower=true) {
$arr2=array();
if(!is_array($arr['0'])){$arr=array($arr);}
foreach($arr as $k=> $v){
foreach($v as $v2){
if($lower==true) {$v2=strtolower($v2);}
if(!isset($arr2[$v2])){
$arr2[$v2]=1;
}else{
$arr2[$v2]++;
}
}
}
return $arr2;
}
Example output (Username => Total posts) also ordered by total posts:
Array
(
[user 1] => 35
[user 2] => 11
[user 3] => 11
[user 4] => 8
[user 5] => 5
[user 6] => 4
[user 7] => 3
[user 8] => 2
[user 9] => 2
[user 10] => 2
[user 11] => 2
[user 12] => 1
[user 13] => 1
[user 14] => 1
[user 15] => 1
[user 16] => 1
[user 17] => 1
[user 18] => 1
[user 19] => 1
[user 20] => 1
[user 21] => 1
[user 22] => 1
[user 23] => 1
[user 24] => 1
[user 25] => 1
[user 26] => 1
)