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
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);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.