生成此字符串的更有效方法

时间:2013-09-13 15:16:12

标签: php

我有一个关键值对的关联数组(根据系统生成它们的方式,键和值完全相同)。我想破坏钥匙或只是价值(这无关紧要) - 有没有办法做到这一点?

现在我有一个foreach循环,这个foreach循环遍历数组以获取值,将其添加到字符串,然后添加逗号。这显然增加了一个比我需要的逗号,因为我不想要一个尾随的逗号。

第一次迭代:

item1,

第二次迭代:

item1, item2,

第三次迭代:

item1, item2, item3,

内爆所有键或数组的所有值(但不是两者)的最有效方法是什么? foreach方法是最好的方法吗?如果是这样,什么是摆脱尾随逗号的最佳方法 - 使用$ count变量,或者只修剪最后一个逗号(看起来后者会更有效,但感觉不那么优雅)。

1 个答案:

答案 0 :(得分:4)

我假设这是PHP;内置函数可以解决这个问题,而不需要循环。

// For the keys
$output = implode(',', array_keys($myArr)).', '; // if you need that trailing comma
$output = implode(',', array_keys($myArr)); // without the trailing comma.

// For the values (note that the keys are discarded by the implode function)
$output = implode(',', $myArr).', '; // if you need that trailing comma
$output = implode(',', $myArr); // without the trailing comma.