user2576401
user2576401

Reputation:

php get key and value from array inside array

Can anyone tell me what am I doing wrong?

Here is my code:

private $user;
private $location;
private $users = array('user1' => array('John Doe' => 'NYC'),
                       'user2' => array('Jane Doe' => 'NYC'));

function setUser($user) {
  foreach ($users[$user] as $key => $value) {
    $this->user = $key;
    $this->location = $value;
  }
}

I want to create methid setUser($user) where you pass in user id, and then return the users name and location.

Example of method call:

setUser(user1);

If the user is set to user1, then return user1 data, if user is set to user2, then return user2 data But the $user variable isn't set to John Doe in my example.

Upvotes: 0

Views: 316

Answers (1)

Leo Bali
Leo Bali

Reputation: 311

function setUser($user) {
  foreach ($this->users[$user] as $key => $value) {
    $this->user = $key;
    $this->location = $value;
  }

Upvotes: 1

Related Questions