Reputation: 2762
I have this array and I want to convert it into string.
I try to get string from php implode()
function but could not get the desired result.
The output I want is arraykey-arrayvalue
,arraykey-arrayvalue
,arraykey-arrayvalue
and so on as long as array limit end.
Array ( [1] => 1 [2] => 1 [3] => 1 )
$data = implode(",", $pData);
//it is creating string like
$data=1,1,1;
// but i want like below
$string=1-1,2-1,3-1;
Upvotes: 2
Views: 3225
Reputation: 21422
You can also use array_map
function as
$arar = Array ( '1' => 1 ,'2' => 1, '3' => 1 );
$result = implode(',',array_map('out',array_keys($arar),$arar));
function out($a,$b){
return $a.'-'.$b;
}
echo $result;//1-1,2-1,3-1;
Upvotes: 2
Reputation: 2827
This can be done using the below code:
$temp = '';
$val = '';
$i=0;
foreach ($array as $key => $value)
{
$temp = $key.'-'.$val;
if($i == 0)
{
$val = $temp; // so that comma does not append before the string starts
$i = 1;
}
else
{
$val = $val.','.$temp;
}
}
Upvotes: 1
Reputation: 41893
You could just gather the key pair values inside an array then implode it:
foreach($array as $k => $v) { $data[] = "$k-$v"; }
echo implode(',', $data);
Upvotes: 6