开发者

Create and array index and value from the two array elements in a while loop

while($info5 = mysql_fetch_array($result)){
        $namelist[] = $info5["name"];
        $idlist[] = $info5["id"]    
    }

I w开发者_StackOverflowant an array which has the entries of the array idlist as it's index and entries of the array namelist as it's values.

Is there a short way to do this?


Like this, if I understand your request. Use $info['id'] as the array key to the accumulating array $namelist (or whatever you decide to call it)

while($info5 = mysql_fetch_array($result)){
    $namelist[$info['id']] = $info5["name"];
}


i'm not sure i understand your question but probably something like this should be fine.

while($info5 = mysql_fetch_array($result)){
    $values[$info5['id']] = $info5;
}


$result = array();
while($info5 = mysql_fetch_array($result))
{
    $id = $info5['id'];
    $name = $info5['name'];

    $result[$id] = $name;
}

This should give the output array $result you want, if I understood correctly.


You can use array_combine as long as the arrays have the same number of values:

$result = false;
if (count($idlist) == count($namelist))
  $result = array_combine($idlist, $namelist);

Check out the docs: http://www.php.net/manual/en/function.array-combine.php

But, I also wonder why you don't just do it in the while loop:

$values = array();
$namelist = array();
$idlist = array();
while($info5 = mysql_fetch_array($result)){
   $namelist[] = $info5["name"];
   $idlist[] = $info5["id"]    
   // this is the combined array you want?
   $values[$info5["id"]] = $info5["name"];
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜