sobhan sobhan - 4 years ago 87
PHP Question

build array in array in loop

This is my code! I'm trying to get from

$test
array and at end show me like
$final
array! tnx to help! code should get domain name and show how many time a userid has been repeated!

<?php

$test = array(
array(
'id' => 1,
'domain' => 'google.com',
'userid' => "123"
),
array(
'id' => 2,
'domain' => 'google.com',
'userid' => "456"enter
),
array(
'id' => 3,
'domain' => 'yahoo.com',
'userid' => "456"
),
array(
'id' => 4,
'domain' => 'google.com',
'userid' => "123"
),
array(
'id' => 5,
'domain' => 'bing.com',
'userid' => "128"
)
);
$i=0;
foreach ($test as $items) {
$domains[$i]=$items['domain'];
$userid[$i]=$items['userid'];
$i++;
}
$domain=array_unique($domains);
$domain1 = array_values($domain);
print_r($domain);
echo '<pre>';
print_r($test);
echo '</pre>';
echo '<hr>';
$d=1; $tedad = 1;
while($d<=4){
$b = 1 ; $c=0;
while ($test[$b]['id']<=4) {
if($test[$b]['domain'] == $domain1[$d])
{
$temp = $test[$b]['userid'];
if(/*$test[$b]['userid'] !==*/ !array_key_exists($domain1[$d] ['userid']){
//$domain1[$d] = array($test[$b]['userid'] => $tedad) ;
echo $temp;
$end = array(
$domain1[$d] => array(
$temp => $tedad )
);

}
else{
$end[$d][$test[$b]['userid']]= $end[$d][$test[$b]['userid']] +1;

}
}
else{
$b++;

}

}
$d++; $tedad = 1;
}

print_r($end);
$final = array(
"google.com" => array(
"123" => 2,
"456" => 1
),
"yahoo.com" => array(
"456" => 1
)
);
echo '<pre>';
print_r($final);
echo '</pre>';
echo '<hr>';

?>

Answer Source
<?php

$test = array(
array(
    'id' => 1,
    'domain' => 'google.com',
    'userid' => "123"
),
array(
    'id' => 2,
    'domain' => 'google.com',
    'userid' => "456"
),
array(
    'id' => 3,
    'domain' => 'yahoo.com',
    'userid' => "456"
),
array(
    'id' => 4,
    'domain' => 'google.com',
    'userid' => "123"
)
);

echo '<pre>';
print_r($test);
echo '</pre>';
echo '<hr>';

$domains = array();
foreach ($test as $value) {
if (!in_array($value['domain'], $domains))
    $domains[$value['domain']] = array();
}
foreach ($domains as $key => $domain) {
foreach ($test as $item) {
    if ($key == $item['domain']) {
        if (isset($domains[$key][$item['userid']])) {
            $domains[$key][$item['userid']] = $domains[$key]      [$item['userid']]+1;
        } else {
            $domains[$key][$item['userid']] = 1;
        }
    }
   }
  }

  echo '<pre>';
  print_r($domains);
 echo '</pre>';
  echo '<hr>';

   // $final = array(
 //     "google.com" => array(
  //        "123" => 2,
   //       "456" => 1
  //    ),
   //   "yahoo.com" => array(
 //         "456" => 1
 //     )
 // );

  // echo '<pre>';
 // print_r($final);
 // echo '</pre>';
 // echo '<hr>';
 ?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download