简体   繁体   中英

Simplest way to print out comma seperated of an assoc array column in PHP (from MYSQL)

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 !

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.

首先排列所有金额的数组,然后内implode结果。

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...

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