如果用户使用ID mysite.com/page.php?id=3
访问我的页面,我希望PHP检查是否在数组中定义了ID,如果为true,则根据其定义的ID从同一数组中返回页面多个用户信息
我的代码:
$userinfo = [
['id' => 3, 'name' => 'username3', 'phone' => '3333'],
['id' => 2, 'name' => 'username2', 'phone' => '2222'],
['id' => 1, 'name' => 'username1', 'phone' => '1111']
];
if (isset($_GET['id']) && isset($userinfo[$_GET['id']])) {
$name = $userinfo[$_GET['name']]; // If I access PHP with '?id=3' wanna 'username3'.
$phone = $userinfo[$_GET['phone']]; // It stores id 3 user phone: '3333'
}
echo $name; // It returns 'name' from array.
echo $phone; // It returns 'phone' from array.
它只是一个基础,我知道它不起作用,代码的任何帮助?提前谢谢。
答案 0 :(得分:2)
$userinfo = [
['id' => 3, 'name' => 'username3', 'phone' => '3333'],
['id' => 2, 'name' => 'username2', 'phone' => '2222'],
['id' => 1, 'name' => 'username1', 'phone' => '1111']
];
if (isset($_GET['id'])){
foreach($userinfo as $user){
if($user['id']==$_GET['id']){
$name = $user['name'];
$phone = $user['phone'];
}
}
}
echo $name;
echo $phone;
答案 1 :(得分:1)
您可以根据需要过滤数组:
$userinfo = [
['id' => 3, 'name' => 'username3', 'phone' => '3333'],
['id' => 2, 'name' => 'username2', 'phone' => '2222'],
['id' => 1, 'name' => 'username1', 'phone' => '1111']
];
$user = null;
if (isset($_GET["id"])) {
$found = array_filter($userinfo, function ($user) {
return isset($user["id"]) && $user["id"] == $_GET["id"];
}); // This will find all users with that id, in case there's more.
$user = !empty($found)?current($found):null; //current() at this point gets the first entry in $found
}
if ($user != null) {
echo $user["name"];
echo $user["phone"];
}
查看array_filter
了解更多详情。
答案 2 :(得分:0)
您可以将此函数用于关联数组的任何深度。对这个函数的约束只是键值不会重复在数组中的任何位置。
<?php
function assoc_in_array($array, $key, $key_value){
$within_array = false;
foreach( $array as $k=>$v ){
if( is_array($v) ){
$within_array = assoc_in_array($v, $key, $key_value);
if( $within_array == true ){
break;
}
} else {
if( $v == $key_value && $k == $key ){
$within_array = true;
break;
}
}
}
return $within_array;
}
$test = [
['id' => 3, 'name' => 'username3', 'phone' => '3333'],
['id' => 2, 'name' => 'username2', 'phone' => '2222'],
];
var_dump(assoc_in_array($test, 'id', '3'));
?>