2

I am trying to convert a multidimensional array into a string.

Till now I have been able to convert a pipe delimited string into an array.

Such as:

group|key|value
group|key_second|value

Will render into the following array:

$x = array(
 'group' => array(
 'key' => 'value',
 'key_second' => 'value'
 ),
);

However, now I want it to be the other way around, where a multidimensional array is provided and I want to convert it to a pipe delimited string just like in the first code example.

Any ideas how to do this ?


PS: Please do note that the array can dynamically have any depth.

For example:

$x['group']['sub_group']['category']['key'] = 'value'

Translates to

group|sub_group|category|key|value

carla
2,1471 gold badge34 silver badges48 bronze badges
asked Sep 15, 2015 at 5:51
5
  • And what you have tried so far can you please update that one.. Commented Sep 15, 2015 at 5:52
  • read the implode section on the php manual php.net/manual/en/function.implode.php Commented Sep 15, 2015 at 5:57
  • implode is useful for single dimensional array, but in this case, this is a multidimensional array, and I need the array keys to be part of the ouput Commented Sep 15, 2015 at 5:58
  • you could use array_reduce() Commented Sep 15, 2015 at 6:04
  • @Alexecus I added a demo for you here stackoverflow.com/a/32578954/4323504 Commented Sep 15, 2015 at 6:23

5 Answers 5

2

I have created my own function: This should have no problem handling even big arrays

function array_to_pipe($array, $delimeter = '|', $parents = array(), $recursive = false)
{
 $result = '';
 foreach ($array as $key => $value) {
 $group = $parents;
 array_push($group, $key);
 // check if value is an array
 if (is_array($value)) {
 if ($merge = array_to_pipe($value, $delimeter, $group, true)) {
 $result = $result . $merge;
 }
 continue;
 }
 // check if parent is defined
 if (!empty($parents)) {
 $result = $result . PHP_EOL . implode($delimeter, $group) . $delimeter . $value;
 continue;
 }
 $result = $result . PHP_EOL . $key . $delimeter . $value;
 }
 // somehow the function outputs a new line at the beginning, we fix that
 // by removing the first new line character
 if (!$recursive) {
 $result = substr($result, 1);
 }
 return $result;
}

Demo provided here http://ideone.com/j6nThF

answered Sep 15, 2015 at 8:03
Sign up to request clarification or add additional context in comments.

1 Comment

Great function. The only problem is that this function always go deeper, so if you have multiples entries that go deep, it doesn't come back to iterate through the second entry.
1

You can also do this using a loop like this:

$x = array(
'group' => array(
 'key' => 'value',
 'key_second' => 'value'
)
);
$yourstring ="";
foreach ($x as $key => $value)
{
 foreach ($x[$key] as $key2 => $value2)
 {
 $yourstring .= $key.'|'.$key2.'|'.$x[$key][$key2]."<BR />";
 }
}
echo $yourstring;

Here is a working DEMO

answered Sep 15, 2015 at 6:17

1 Comment

Hi, I've checked your demo. It works for a fixed depth of array, which is in this case is 2 levels. It should work for any depth.
1

This code should do the thing.

You needed a recursive function to do this. But be careful not to pass object or a huge array into it, as this method is very memory consuming.

function reconvert($array,$del,$path=array()){
 $string="";
 foreach($array as $key=>$val){
 if(is_string($val) || is_numeric($val)){
 $string.=implode($del,$path).$del.$key.$del.$val."\n";
 } else if(is_bool($val)){
 $string.=implode($del,$path).$del.$key.$del.($val?"True":"False")."\n";
 } else if(is_null($val)){
 $string.=implode($del,$path).$del.$key.$del."NULL\n";
 }else if(is_array($val)=='array') {
 $path[]=$key;
 $string.=reconvert($val,$del,$path);
 array_pop($path);
 } else {
 throw new Exception($key." has type ".gettype($val).' which is not a printable value.');
 }
 }
 return $string;
}

DEMO: http://ideone.com/89yLLo

answered Sep 15, 2015 at 6:56

2 Comments

nicely done. I've tried to test your code, and it seems that a delimiter is being appended on the first entries. See here ideone.com/ZlOLEq
Ah, yeah, didnt think of that case. Here is a fixed code. ideone.com/oypu7F
0

You can do it by

  1. Look at serialize and unserialize.
  2. Look at json_encode and json_decode
  3. Look at implode

And Possible duplicate of Multidimensional Array to String

answered Sep 15, 2015 at 5:59

1 Comment

the topic you posted seems to only take care of array values, without taking in consideration the array keys (like on my example). JSON encode then str_replace seems to be a solution, but I presume there is a much better way to do it
0

You can do this if you specifically want a string :

$x = array(
'group' => array(
 'key' => 'value',
 'key_second' => 'value'
),
 'group2' => array(
 'key2' => 'value',
 'key_second2' => 'value'
),
);
$str='';
foreach ($x as $key=>$value)
{
 if($str=='')
 $str.=$key;
 else
 $str.="|$key";
 foreach ($value as $key1=>$value1)
 $str.="|$key1|$value1";
}
echo $str; //it will print group|key|value|key_second|value|group2|key2|value|key_second2|value
answered Sep 15, 2015 at 6:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.