Reputation: 2706
Hi i am using CakePHP version 2.x
I am print my array using
pr($this->request->params['named']);
//Output
Array
(
[street_name] => Bhubaneswar
[house_number] => 1247
[phone] => xxxxxxxx
[zip] => xxxxx
)
In above array i want to view looks like
/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx
How to convert above array in string format?
Upvotes: 0
Views: 156
Reputation: 2916
Try this:
$strResult = "";
foreach ($this->request->params['named'] as $key=>$value){
$strResult .= "/{$key}:{$value}";
}
Upvotes: 3
Reputation: 553
<?php
$array = array(
'street_name' => 'Bhubaneswar',
'house_number' => '1247',
'phone' => 'xxxxxxxx',
'zip' => 'xxxxx',
);
while (current($array)) {
echo '/'.key($array).':'.$array[key($array)];
next($array);
}
?>
this will return
/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx
Upvotes: 0
Reputation: 20250
As a one-liner:
echo '/' . str_replace('=', ':', http_build_query($array, '', '/'));
Would output:
/street_name:Bhubaneswar/house_number:1247/phone:xxx/zip:xxx
Upvotes: 2
Reputation: 515
foreach (array_expression as $key => $value){
echo "/". $key . ":" . $value;
}
Upvotes: 1
Reputation: 3648
function implode_with_keys($glue, $separator, $pieces)
{
$string = '';
foreach ($pieces as $key => $value) {
$string .= $glue . $key . $separator . $value;
}
return $string;
}
In your case you'd use it like this:
implode_with_keys('/', ':', $this->request->params['named']);
This will return the desired string /street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx
.
Upvotes: 0
Reputation: 23816
Try following code:
$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
Upvotes: 0
Reputation: 3464
The most easy and speedy solution.
$result = '';
foreach ($this->request->params['name'] as $k => $v) {
$result .= sprintf('/%s:%s', $k, $v);
}
Upvotes: 2