3

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?

Justin Erswell
  • 688
  • 7
  • 42
  • 87

4 Answers4

6

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));
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
3

You're just about there.

$tokens = array();
foreach($result as $device){
    $tokens[] = $device['dToken'];
}
echo implode(',', $tokens);
jeremyharris
  • 7,884
  • 22
  • 31
2

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.

mb14
  • 22,276
  • 7
  • 60
  • 102
  • `join` is an alias for `implode`. – Sven van Zoelen Aug 08 '12 at 18:26
  • you are right, PHP is not my first language, so I use join (as lots of other language use 'join'). I'll edit my answer – mb14 Aug 08 '12 at 18:29
  • 3
    However, why does PHP provide alias if you *can't* use them ? ;-) – mb14 Aug 08 '12 at 18:30
  • +1 for the edit :) But serious when coding it is important to always try to prevent WTF's for other people reading / reviewing your code. Although it is not a big one it is always better to prevent it when possible. Besides PHP has a lot of WTFs already built-in so I always try to steer away from them when possible just to prevent confusion and errors. P.S. there was nothing "wrong" with your answer it could just be improved imho :) – PeeHaa Aug 08 '12 at 19:03
-1
callback = function($row){
    return $row['dToken'];
}

implode(",",array_map(callback,$result));
Eugene H
  • 425
  • 3
  • 7