Jump to content

Confused by multidimensional arrays...


Sabmin

Recommended Posts

I have an array titled $uhits that looks like this:

 

Array (

[0] => Array (

[user] => test

[hits] => 20 )

[3] => Array (

[user] => test3

[hits] => 6 )

[4] => Array (

[user] => test4

[hits] => 6 )

[1] => Array (

[user] => test1

[hits] => 4 ) 

[2] => Array (

[user] => test2

[hits] => 4 ) )

 

I've searched and tried so many different functions and  am losing my mind after trying for 3 hours to be able to search for a specific user's value and then display it and the hits value.  How in the world can I achieve this?

Link to comment
https://forums.phpfreaks.com/topic/210486-confused-by-multidimensional-arrays/
Share on other sites

Okay, I've recreated your array for this little example, but here is how you can do it. I've used a function, you don't have to use a function. And in the function I'm just returning the users hits, you could choose to return the array so you can access their name and hits if you want.

 

function get_users_hits($array, $username){
// Use foreach to loop through each of the users arrays.
foreach($array as $users){
	// $users is now an array, with the keys being associative (user and hits)
	if($users['user'] == $username){
		// If we found a username which matched the username we requested for the function, return the hits
		return $users['hits'];
	}
}

// If we couldn't find any user by that name, return false.
return false;
}

$array = array(
array(
	'user' => 'test',
	'hits' => 20
),
array(
	'user' => 'test3',
	'hits' => 6
),
array(
	'user' => 'test4',
	'hits' => 6
),
array(
	'user' => 'test1',
	'hits' => 4
),
array(
	'user' => 'test2',
	'hits' => 4
)
);

$user = 'test3';
echo "Hits by " . $user . ": " . get_users_hits($array, $user);

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.