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条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料