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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥30 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 数电几道习题,写出作答过程,ai一律不采用
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU
  • ¥30 51单片机C语言数码管驱动单片机为AT89C52