开发者

php 2 dimensional array retrieve value?

开发者 https://www.devze.com 2023-02-09 17:05 出处:网络
$useridtofind= 123; $users=array(); while ($data = mysql_fetch_array ($result)) { $userid = $data[\'userid\'];
$useridtofind= 123;

$users=array();

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

        $userid = $data['userid'];
 开发者_StackOverflow社区   $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?      
    }
}


You already use the id to index the array.

Just use:

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

EDIT: Added isset check and reduced the number of times referencing the same array element


You seem to be using the user id as the index of the user in the array. If this is the case, you shouldn't be using a for loop, you should just check if the key exists within the array:

$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";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消