简体   繁体   中英

How to format output array correctly in php

I need to produce an array that is formatted as follows:

Array(  
Array([100000116287110]=>  
Array([name] => Bryce [image] => abcd.png))  
Array([100003019827186]=>  
Array([name] => Ross [image] => defg.png))  
)  

The data to produce the array comes from 2 different sources and is fed to a function.

The function call is lookupUserData($a, array(“name”, “image”)) //this has been set up so other details from the user table can be called simply by adding the field name in the array. $a is formated as $a = “100000116287110,100003019827186”

The current code I am using for the function is as follows:

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
}

This however returns the result as follows:

Array(  
Array([0]=>[100000116287110]  
Array([name] => Bryce [image] => abcd.png))  
Array([1]=>[100003019827186]  
Array([name] => Ross [image] => defg.png))  
)

I know I have missed something simple but just cannot seem to get this right!

Something like this:


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM