简体   繁体   English

PHP从数组内部的数组获取键和值

[英]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. 我想创建方法setUser($user) ,您在其中传递用户ID,然后返回用户名和位置。

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. 如果将用户设置为user1,则返回user1数据,如果将用户设置为user2,则返回user2数据但是在我的示例中,$ user变量未设置为John Doe。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM