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
  • 1,970
  • 1
  • 31
  • 44
Alexecus
  • 69
  • 1
  • 7

5 Answers5

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

Alexecus
  • 69
  • 1
  • 7
  • 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. – carla Mar 07 '16 at 14:43
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

Luthando Ntsekwa
  • 4,192
  • 6
  • 23
  • 52
  • 1
    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. – Alexecus Sep 15 '15 at 06:29
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

Drath Vedro
  • 330
  • 2
  • 10
  • nicely done. I've tried to test your code, and it seems that a delimiter is being appended on the first entries. See here http://ideone.com/ZlOLEq – Alexecus Sep 15 '15 at 07:22
  • Ah, yeah, didnt think of that case. Here is a fixed code. http://ideone.com/oypu7F – Drath Vedro Sep 15 '15 at 07:47
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

Community
  • 1
  • 1
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
  • 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 – Alexecus Sep 15 '15 at 06:17
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
Amit.S
  • 431
  • 2
  • 9