PHP遍历多维数组

2024-12-15 17:39:28
推荐回答(3个)
回答1:

你的意思是用户输入nickname 比如输'user2' 然后你这边取user2对应的password吗?

$data = [
    'user'=>[
        "0a8a5986a6c18920fd456fdfbb048913"=>[
        "nickname"=>"user1",
        "userName"=>"username",
        "passWord"=>"password",
        "status"=>1,
        ],
        "0ffb201c2335a784abd19c2985797711"=>[
        "nickname"=>"user2",
        "userName"=>"username",
        "passWord"=>"password",
        "status"=>1,
        ],
    ]
];
//第一种情况是user数组里有多个叫user2的nickname,这样查出的password也会有多个,所以就需要循环来处理了
$nickname='user2';//这里是用户输入的值
$password=[];
foreach ($data['user'] as $val){
    if($val['nickname']==$nickname){
        $password[]=$val['passWord'];
    }
}
print_r($password);
//第二情况就是user数组里只会有一个叫user2的nickname,这样只会查出一个password
$nickname='user2';//这里是用户输入的值
$user=array_column($data['user'],null,'nickname');
$password=$user[$nickname]['passWord'];
echo $password;

回答2:

仅供参考

$users = [
"0a8a5986a6c18920fd456fdfbb048913"=>[
"nickname"=>"user1",
"userName"=>"username",
"passWord"=>"password",
"status"=>1,
],
"0ffb201c2335a784abd19c2985797711"=>[
"nickname"=>"user2",
"userName"=>"username",
"passWord"=>"password",
"status"=>1,
]
];

$targetNickname = "user1";

foreach($users as $user)
{
if(isset($user['nickname']) && $user['nickname'] == $targetNickname)
{
echo isset($user['passWord'])?$user['passWord']:null;
break;
}
}

?>

回答3:

$arr = json获取的数组;
$nickname = '****';
$password = '';
foreach($arr as $key=>$v)
{
if(isset($v['nickname']) && $v['nickname']==$nickname){
$password = $v['password'];

}
}