PHP:将多维数组转换为字符串

时间:2022-10-22 22:57:40

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'

$ x(“集团”)(“sub_group”)(“类别”)(“关键”)=“价值”

Translates to

翻译为

group|sub_group|category|key|value

集团| sub_group关键| | |类别值

5 个解决方案

#1


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

这里提供演示http://ideone.com/j6nThF

#2


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

这是一个可用的演示

#3


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

演示:http://ideone.com/89yLLo

#4


0  

You can do it by

你可以通过

  1. Look at serialize and unserialize.
  2. 看看序列化和反序列化。
  3. Look at json_encode and json_decode
  4. 看看json_encode和json_decode
  5. Look at implode
  6. 看内爆

And Possible duplicate of Multidimensional Array to String

以及多维数组到字符串的可能重复

#5


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

#1


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

这里提供演示http://ideone.com/j6nThF

#2


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

这是一个可用的演示

#3


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

演示:http://ideone.com/89yLLo

#4


0  

You can do it by

你可以通过

  1. Look at serialize and unserialize.
  2. 看看序列化和反序列化。
  3. Look at json_encode and json_decode
  4. 看看json_encode和json_decode
  5. Look at implode
  6. 看内爆

And Possible duplicate of Multidimensional Array to String

以及多维数组到字符串的可能重复

#5


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