Jump to content

Selecting unknown array from multi-dimensional arrays


dota

Recommended Posts

Hi,

 

I have a multi dimensional array with a value that iterates once every time the user visits the page:

<?php
<snip>
++$pageVisits[$username]['visits'] ;
</snip>
?>

So this looks like:

Array

(

    [james] => Array

        (

            [visits] => 1

        )

)

When you print_r($pageVisits) and if 'james' was to visit the page again, [visits] would become 2 and so on and so forth.

Now say later on I want to print every person who visited the page and how many time's he/she visited it, I would do:

<?php
foreach($pageVisits as $visitor => $visits)
{
    	echo 'Visitor: '.$visitor.'; Visits: '.$visits['visits'].'<br />';
}
?>

Now I want to select the person that visited the page the most and how many times they visited.

To get the number of visits I'd use max():

<?php
$maxVisits = max($visits);
?>

 

But I can't figure out how I'd select the username of the person that visited the most?

 

Everything works fine, there are no problems with the code, I just need to work out how I could take the username array from the maxVisits so I'll have a $maxVisitor as well.

 

Oh and I would like to stick to using this method because I'm just playing around with new things, I know there are much easier ways, but I won't learn how to overcome this problem if i try doing it a different way.

 

Thanks

How about:

<?php
$max_visitor = Array();
$max_visits = 0;
foreach($pageVisits as $visitor => $visits) {
    if($visits>$max_visits) {
        $max_visits = $visits;
        $max_visitor = $visitor;
    }
}
echo "Here's the stats for the max visiting user:\n";
var_dump($max_visitor);
?>

 

Hope that helps.

How about:

<?php
$max_visitor = Array();
$max_visits = 0;
foreach($pageVisits as $visitor => $visits) {
    if($visits>$max_visits) {
        $max_visits = $visits;
        $max_visitor = $visitor;
    }
}
echo "Here's the stats for the max visiting user:\n";
var_dump($max_visitor);
?>

 

Hope that helps.

Brilliant, I ended up using a modified version of this for what I needed and it worked great.

Cheers php_tom ;)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.