如何使用数组的键构造字符串


How to construct a string using the keys of an array?

我需要帮助来构造一个基于数组键值使用逗号连接的字符串。可以使用foreach循环来实现,但是有没有类似于使用implode()的方法?

这是我使用的示例数组,

array(5) { 
    [2280]=> string(1) "1" 
    [2138]=> string(1) "1" 
    [3194]=> string(1) "1" 
    [2396]=> string(1) "1" 
    [2944]=> string(1) "1" 
}

提前致谢!!

假设你的数组被命名为$array,你可以这样做:

implode(',',array_keys($array))

array_keys 将在另一个数组中返回数组的键,然后用于将键内爆到您想要的字符串中。

这将生成以下字符串:

"2280,2138,3194,2396,2944"
可以

像这样做:

echo implode(', ', array_keys(array(2280 => '1', 2138 => '1')));

输出:

2280, 2138