dreamice2013 2016-08-05 06:42
浏览 37
已采纳

在php中给出一个模式,将字符串分段为多个字符串

I'm stuck and I just need a pointer. I have this string with special characters retrieved from db and i want to segment it to many strings or arrays and in the process i want to exchange those characters with "()". |p| stands for parent. |c| child.

Example sentence is :

my beautiful car is awesome

*where my , beautiful and car have a parent-child relationship.

The pattern for it :

|p|my|c||p|beautiful|c||c||p|car|p|is|p|awesome

In case you need to see the original array:

Array
(
[0] => Array
    (
        [name] => |p|my
        [parent_id] => 0
        [child] => Array
            (
                [0] => Array
                    (
                        [name] => |c||p|beautiful
                        [parent_id] => 1
                        [child] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => |c||c||p|car
                                        [parent_id] => 2
                                    )

                            )

                    )

            )

    )

[1] => Array
    (
        [name] => |p|is
        [parent_id] => 0
    )

[2] => Array
    (
        [name] => |p|awesome
        [parent_id] => 0
    )

)

The ultimate goal after segmenting and replacement is: ((My(beautiful(car)) (is)(awesome))

  • 写回答

2条回答 默认 最新

  • dppx9253 2016-08-05 14:28
    关注
    <?php
    $items =
    [
        [
            'name'  => 'foo',
            'children' => 
                [
                    [
                        'name'  => 'bar',
                        'children' => 
                            [
                                [
                                    'name' => 'baz',
                                ]
                            ]
                    ]
                ]
        ],
        [
            'name'  => 'bat',
        ],
        [
            'name'  => 'man',
        ]
    ];
    
    function bracketize($array) {
        $output = '';
        foreach($array as $item) {
            $output .= '(';
            $output .=  $item['name'];
            if(isset($item['children']))
                $output .= bracketize($item['children']);
            $output .= ')';
        }
    
        return $output;
    }
    
    $output = '(' . bracketize($items) . ')';
    print $output;
    

    Output:

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度