如何在PHP中将数组转换为字符串?

时间:2014-07-11 06:56:47

标签: php arrays cakephp

您好我正在使用CakePHP版本2.x

我使用

打印我的数组
pr($this->request->params['named']);

//Output
Array
(
    [street_name] => Bhubaneswar
    [house_number] => 1247
    [phone] => xxxxxxxx
    [zip] => xxxxx
)

在上面的数组中我想查看看起来像

/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx

如何以字符串格式转换上面的数组?

7 个答案:

答案 0 :(得分:3)

试试这个:

$strResult = "";
foreach ($this->request->params['named'] as $key=>$value){
    $strResult .= "/{$key}:{$value}";
}

答案 1 :(得分:2)

最简单快捷的解决方案。

$result = '';
foreach ($this->request->params['name'] as $k => $v) {
    $result .= sprintf('/%s:%s', $k, $v);
}

答案 2 :(得分:2)

作为一个单行:

echo '/' . str_replace('=', ':', http_build_query($array, '', '/'));

输出:

/street_name:Bhubaneswar/house_number:1247/phone:xxx/zip:xxx 

答案 3 :(得分:1)

foreach (array_expression as $key => $value){
    echo "/". $key . ":" . $value;
}

答案 4 :(得分:0)

请尝试以下代码:

$ar = array('street_name' => 'Bhubaneswar',
    'house_number' => 1247,
    'phone' => 'xxxxxxxx',
    'zip' => 'xxxxx');
echo convert($ar);

function convert($ar)
{
    $str = '';
    foreach($ar as $i=>$k)
    {
        $str .= '/'.$i.':'.$k;
    }
    return $str;
}

输出

/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx

答案 5 :(得分:0)

function implode_with_keys($glue, $separator, $pieces)
{
    $string = '';
    foreach ($pieces as $key => $value) {
        $string .= $glue . $key . $separator . $value;
    }
    return $string;
}

在您的情况下,您可以像这样使用它:

implode_with_keys('/', ':', $this->request->params['named']);

这将返回所需的字符串/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx

答案 6 :(得分:0)

<?php
$array = array(
    'street_name' => 'Bhubaneswar',
    'house_number' => '1247',
    'phone' => 'xxxxxxxx',
    'zip' => 'xxxxx',
);

while (current($array)) {

        echo '/'.key($array).':'.$array[key($array)];

    next($array);
}
?>

这将返回

/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx