简体   繁体   English

最简单的方法来打印PHP中的assoc数组列的逗号分隔符(来自MYSQL)

[英]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. 我有一个mysql fetch,它用数据库中的列填充关联数组。 One of the columns names is AMOUNT. 列名称之一是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: 我要做的就是回显AMOUNT,如下所示:

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. $array包含所有行的数组。

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: 如果您使用的是PHP 5.3+,则以下内容也适用:

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

Courtesy of Mearlyn 由Mearlyn提供

More 更多

  • implode - Takes an array and a delimiter and returns a string of 'delimiter' separated values of the array. implode一个数组和一个定界符,并返回一个由'delimiter'分隔的数组值的字符串。

首先排列所有金额的数组,然后内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) 做到这一点尾随或标题逗号,然后用http://php.net/manual/en/function.rtrim.php (或http://php.net/manual/en/function.ltrim.php分别)

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. 在2个成员数组上进行了10000000次运行测试。

Solution suggested by Truth requires 171 second to run, solution suggested by Mearlyn required 358!! 真相建议的解决方案需要171秒才能运行,米林建议的解决方案需要358秒! seconds to run and my solution requires only 18 seconds!! 秒运行,我的解决方案只需要18秒!

I used pastebin.com/fKbxfpy1 to get mentioned times... 我用pastebin.com/fKbxfpy1来获得提到的时间...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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