0

I have an array it contains key and value. i would like to converting into a string.

array(
 [business_type]=>'cafe'
 [business_type_plural] => 'cafes'
 [sample_tag]=>'couch'
 [business_name]=>'couch cafe'
 )

Expected Output:

business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe

NOTE:

I was searching in StackOverflow and found the below question and it has answer. I want exactly reverse one.

converting string containing keys and values into array

1
  • use implode instead of explode =) Commented Dec 7, 2012 at 16:52

3 Answers 3

2

Try

$data = array();
foreach($arr as $key=>$value) {
  $data[] = $key.','.$value;
}
echo implode('|',$data);

Another Solution:

function test_alter(&$item1, $key, $delimiter)
{
    $item1 = "$key".$delimiter."$item1";
}

array_walk($arr, 'test_alter',',');
echo implode('|',$arr);
Sign up to request clarification or add additional context in comments.

Comments

1

Use the foreach() function to go through the array and string the keys/values together...

Assuming your array is called $array

$result = "";
foreach($array as $key => $value){
    $result .= $key . "," . $value . "|";
}

It's as simple as that.

EDIT - Thanks Nelson

After that, lost the last |

$result = rtrim($result, "|");

1 Comment

Don't forget to remove the extra | at the end. That's why I prefer GBD's implode method.
0

try this

$pieces=array();
foreach(array('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3') as $k=>$v)
{
    $pieces[]=$k.','.$v;
}
echo implode('|', $pieces);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.