dsunj08246
2015-09-15 05:51
浏览 281
已采纳

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

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • dongzhiqi0332 2015-09-15 08:03
    已采纳

    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

    已采纳该答案
    打赏 评论
  • dongming5444 2015-09-15 05:59

    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

    打赏 评论
  • douyao1878 2015-09-15 06:12

    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
    
    打赏 评论
  • douxie4583 2015-09-15 06:17

    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

    打赏 评论
  • douershuang7356 2015-09-15 06:56

    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."
    ";
            } else if(is_bool($val)){
                $string.=implode($del,$path).$del.$key.$del.($val?"True":"False")."
    ";
            } else if(is_null($val)){
                $string.=implode($del,$path).$del.$key.$del."NULL
    ";
            }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

    打赏 评论

相关推荐 更多相似问题