开发者

Multi dimensional array

开发者 https://www.devze.com 2023-01-27 20:50 出处:网络
Have j开发者_开发知识库ust come across a problem where I believe this is the solution. At the moment I have the following code:

Have j开发者_开发知识库ust come across a problem where I believe this is the solution.

At the moment I have the following code:

function siteUsers()
{
    global $database;
    $q = "SELECT username, id FROM ".TBL_USERS."";
    return mysql_query($q, $this->connection);
}

function generateUserArray() 
{
    $u = array();
    $i = array();
    $result = $this->siteUsers();
    while( $row=mysql_fetch_assoc($result)) 
    {
        $u[] = $row['username'];
        $i[] = $row['id'];
    }
    return $u, $i;
}

As you can see, when I then go onto use foreach, the u and i get split apart. Is there anyway that I could keep them together?

foreach ($u as $username) {
  echo"<option value='$i'>$username</option>";
}

What I need it the option value to be the id and the visual value to be the username. Is this possible? Thanks


Use an associative array linking the ID to the username. I'm assuming here the IDs are unique.

$users = array();
while( $row=mysql_fetch_assoc($result)) 
{
    $users[$row['id']] = $row['username'];
}
return $users;

Then:

foreach ($users as $id => $username)
{
    echo "<option value='$id'>$username</option>";
}


foreach($u as $idx => $username)
{ 
   echo"<option value='".$i[$idx]."'>$username</option>";
}

assuming equal length and that php function can return two values :\

0

精彩评论

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

关注公众号