2

I have a mysql fetch that is populating an associative array with columns from the DB. One of the columns names is AMOUNT. so it looks like this:

Array ( [0] => Array ( [ID] => 259 [YEARMONTH] => 201105 [AMOUNT] => 54 [VALUE] => 12 ) [1] => Array ( [ID] => 259 [YEARMONTH] => 201106 [AMOUNT] => 32 [VALUE] => 34 ) )

All I want to do is echo the AMOUNTs like this:

54,32

So that I don't have trailing or heading commas.

Any suggestion for an elegant solution for this ? Thanks !

Ted
  • 3,805
  • 14
  • 56
  • 98

3 Answers3

5

Preconditions

  • $array contains the array for all rows.

Code

foreach ($array as $row) {

    $newArray[] = $row['AMOUNT']; //Add it to the new array

}
echo implode(',',$newArray); //Implode the array and echo it out.

If you are using PHP 5.3+, this following also works:

echo implode(",",array_map(function($a) { return $a["AMOUNT"]; }, $array));

Courtesy of Mearlyn

More

  • implode - Takes an array and a delimiter and returns a string of 'delimiter' separated values of the array.
Community
  • 1
  • 1
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
1

First make an array of all amounts and then implode the result.

TimWolla
  • 31,849
  • 8
  • 63
  • 96
1

Do it WITH trailing or heading comma and then use http://php.net/manual/en/function.rtrim.php (or http://php.net/manual/en/function.ltrim.php respectively)

Code

$a = '';
foreach ($test as $t)
    $a .= $t['AMOUNT'] . ',';
$result = rtrim($a, ',');

Alternatives

Approaches with implode are correct too, but my solution is faster.

Performance

Tested on 2 member array with 10000000 runs.

Solution suggested by Truth requires 171 second to run, solution suggested by Mearlyn required 358!! seconds to run and my solution requires only 18 seconds!!

I used pastebin.com/fKbxfpy1 to get mentioned times...

Community
  • 1
  • 1
graywolf
  • 7,092
  • 7
  • 53
  • 77
  • No need. There are native, built-in functions to do what he wants. – Madara's Ghost Oct 16 '11 at 10:35
  • I agree, and they are faster on one dimensional array. But there it will mean two passes through array as described in PS – graywolf Oct 16 '11 at 10:38
  • If you are going for performance, you really should use my approach (the one using rtrim). Solution suggested by Truth requires 171 second to run, solution suggested by Mearlyn required 358!! seconds to run and my solution requires only 18 seconds!! I used http://pastebin.com/fKbxfpy1 to get mentioned times... – graywolf Oct 16 '11 at 12:33