在PHP中将数组合并为字符串

时间:2011-10-27 07:02:52

标签: php

我在PHP中有一个以下数组

$arrOrders['remains'] = 'ASC';
$arrOrders['rate']    = 'DESC';

如何将组合使用到像本机函数一样的字符串?

$str = 'remain ASC, rate DESC';

4 个答案:

答案 0 :(得分:5)

$a = array(
    'remains' => 'ASC',
    'rate'      => 'DSC'
);  

echo implode(', ', array_map(function($v1, $v2) {
    return sprintf('%s %s', $v1, $v2);
}, array_keys($a), array_values($a)));
// remains ASC, rate DSC

答案 1 :(得分:3)

使用foreach和implode()

foreach ($arrOrders as $key => $val) {
$temp[] = "$key $val";
}
$order = implode(',', $temp);

答案 2 :(得分:2)

你可以这样做:

$string = '';
foreach($arrOrders as $key => $value)
   $string = $string . "$key $value, ";
$string  = rtrim($string, ', '); // cut the last comma at the end of the string

echo $string // remains ASC, rate DESC

答案 3 :(得分:1)

您正在寻找implode,但它不包含密钥,但页面上的第一条评论是包含密钥的功能

/**
 * Implode an array with the key and value pair giving
 * a glue, a separator between pairs and the array
 * to implode.
 * @param string $glue The glue between key and value
 * @param string $separator Separator between pairs
 * @param array $array The array to implode
 * @return string The imploded array
 */
function array_implode( $glue, $separator, $array ) {
    if ( ! is_array( $array ) ) return $array;
    $string = array();
    foreach ( $array as $key => $val ) {
        if ( is_array( $val ) )
            $val = implode( ',', $val );
        $string[] = "{$key}{$glue}{$val}";

    }
    return implode( $separator, $string );

}


$arrOrders = array(
    'remains' => 'ASC',
    'rate'      => 'DSC'
);
$str = array_implode( ' ', ', ', $arrOrders);