我需要生成一个格式如下的数组:
Array(
Array([100000116287110]=>
Array([name] => Bryce [image] => abcd.png))
Array([100003019827186]=>
Array([name] => Ross [image] => defg.png))
)
产生阵列的数据来自两个不同的来源,并被送到一个函数。
函数调用是lookupUserData($a, array(“name”, “image”))
//已设置此项,因此只需在数组中添加字段名称即可调用用户表中的其他详细信息。
$ a格式为$a = “100000116287110,100003019827186”
我用于该功能的当前代码如下:
function lookupUserData($f,$u)
{
$f = explode(",",$f); //user id from string – converts string to array ([0] =>100000116287110 [1] =>100003019827186)
$u = implode(",",$u); //fields to extract – converts array(“name”,”image”) to name,image
$r=array(); //define results array`
$nr = count($f); //count number of ids to process
for($i=0; $i<$nr; $i++) { //process each id in $f array
$r[]=$f[$i];
$res = mysql_query("SELECT {$u} FROM users where id ={$f[$i]}"); //query user table
$val= mysql_fetch_assoc($res); //return requested fields ($u) from user table
array_push($r, $val); //add values to array $r
}
print_r ($r); //check array output – testing only
return $r; //return array for processing
}
然而,返回结果如下:
Array(
Array([0]=>[100000116287110]
Array([name] => Bryce [image] => abcd.png))
Array([1]=>[100003019827186]
Array([name] => Ross [image] => defg.png))
)
我知道我错过了一些简单的东西,但似乎无法做到这一点!
答案 0 :(得分:1)
这样的事情:
$r= array();
for($i=0; $i<$nr; $i++) { //process each id in $f array
$res = mysql_query("SELECT {$u} FROM users where id ={$f[$i]}"); //query user table
$val= mysql_fetch_assoc($res); //return requested fields ($u) from user table
$r[$f[$i]] = $val;
}