PHP数组以逗号分隔列表
问题描述:
I have a list of items from a database being parse in an array
Array
(
[0] => Array
(
[dToken] => 731fea87ea9dc61f16e93f1ad2b964bf1926633acac151c1853ab91ea0465228
[0] => 731fea87ea9dc61f16e93f1ad2b964bf1926633acac151c1853ab91ea0465228
)
[1] => Array
(
[dToken] => d890a5002f7da8bd35f6cae50e597d6f11554b26ba686bc7314afe77d1b36a61
[0] => d890a5002f7da8bd35f6cae50e597d6f11554b26ba686bc7314afe77d1b36a61
)
)
I need to get all of the dTokens and list them out in a variable with each dToken seperated by a comma except the last in the list.
foreach($result as $device['dToken'] => $token){
//$devices = $token['dToken'];
print_r($token['dToken']);
}
Any help please?
答
You're just about there.
$tokens = array();
foreach($result as $device){
$tokens[] = $device['dToken'];
}
echo implode(',', $tokens);
答
To answer the question corresponding to the tile (transform an Array to a list with separator) use the implode
function. To generate a CSV I would google php CSV
, I'm sure there are already lots of function to do it.
答
callback = function($row){
return $row['dToken'];
}
implode(",",array_map(callback,$result));
答
You could just build the string:
$cvsString = '';
$delimiter = '';
foreach($result as $device){
$cvsString.= $delimiter . $device['dToken'];
$delimiter = ',';
}
var_dump($cvsString);
Or you could first build in array:
$cvsArray = array();
foreach($result as $device){
$cvsArray[] = $device['dToken'];
}
var_dump(implode(',', $cvsArray));