php 2维数组检索值?

时间:2011-02-11 01:18:00

标签: php arrays associative

$useridtofind= 123;

$users=array();

while ($data = mysql_fetch_array ($result))
{

        $userid = $data['userid'];
    $age = $data['age'];
    $gender = $data['gender'];
    $dob = $data['dob'];

    $users[$userid] => array(
        'age'=> $age, 
        'gender'=> $gender, 
        'dob' => $dob
        )
}


$useridtofind=123;

for($v=0; $v< count($users); $v++)
{
    if($users[$v]== $useridtofind)
    {
        //how to go with grab value of age, gender, dob  here?      
    }
}

2 个答案:

答案 0 :(得分:2)

您已经使用id来索引数组。

只需使用:

if (isset($users[$usertofind])) {
  $user = $users[$usertofind]; 
  echo $user['age'];
  echo $user['dob'];
  echo $user['gender'];
}

编辑:添加了isset检查并减少了引用相同数组元素的次数

答案 1 :(得分:0)

您好像使用用户ID作为数组中用户的索引。如果是这种情况,则不应使用for循环,只需检查数组中是否存在密钥:

$useridtofind = 123;

if (array_key_exists($useridtofind, $users)) {
  $user = $users[$useridtofind];

  echo "User exists: ", $user['age'], '/', $user['gender'], '/', $user['dob'];
} else {
  echo "User doesn't exist";
}