I want the array and array value to separate the string with commas

I have this array and I want to convert it to a string.
I am trying to get a string from php implode() function but cannot get the desired result.
The output I want is arraykey-arrayvalue , arraykey-arrayvalue , arraykey-arrayvalue , etc. Until the limit of the array ends.

  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; 
+5
source share
3 answers

You can simply collect the key pair values ​​inside the array, and then blow it up:

 foreach($array as $k => $v) { $data[] = "$k-$v"; } echo implode(',', $data); 
+5
source

You can also use the 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; 
+2
source

This can be done using the code below:

 $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; } } 
+1
source

All Articles