Home >Backend Development >PHP Tutorial >Convert one-dimensional data to multi-dimensional in php_PHP tutorial

Convert one-dimensional data to multi-dimensional in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:30:35950browse

I saw a friend’s request in the forum today, and I witnessed that the moderators of csdn are worthy of being powerful! ! ! Save it for later use when needed.


The string is:

喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHByZSBjbGFzcz0="brush:java;">1 = Optical mouse 2 = Mechanical mouse 3 = no mouse 1.1 = black optical mouse 1.2 = red optical mouse 1.2.1 = Bluetooth Red Optical Mouse
The moderator’s answer is:

<?php
$s =<<< TXT
1 = 光电鼠标
2 = 机械鼠标
3 = 没有鼠标
1.1 = 黑色光电鼠标
1.2 = 红色光电鼠标
1.2.1 = 蓝牙红色光电鼠标
TXT;
 
$res = array();
foreach(preg_split("/[\r\n]+/", $s) as $r) {
  list($k, $txt) = explode(' = ', $r);
  $p =& $res;
  foreach(explode('.', $k) as $v) {
    if(! isset($p[$v])) $p[$v] = array('txt' => $txt, 'child' => array());
    $p =& $p[$v]['child'];
  }
}
 
print_r($res);
?>

The printed array is:

Array
(
    [1] => Array
        (
            [txt] => 光电鼠标
            [child] => Array
                (
                    [1] => Array
                        (
                            [txt] => 黑色光电鼠标
                            [child] => Array
                                (
                                )
 
                        )
 
                    [2] => Array
                        (
                            [txt] => 红色光电鼠标
                            [child] => Array
                                (
                                    [1] => Array
                                        (
                                            [txt] => 蓝牙红色光电鼠标
                                            [child] => Array
                                                (
                                                )
 
                                        )
 
                                )
 
                        )
 
                )
 
        )
 
    [2] => Array
        (
            [txt] => 机械鼠标
            [child] => Array
                (
                )
 
        )
 
    [3] => Array
        (
            [txt] => 没有鼠标
            [child] => Array
                (
                )
 
        )
 
)
I laughed when I saw these comments:





www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/765064.htmlTechArticleToday I saw a friend’s request in the forum, and I witnessed that the moderators of csdn are worthy of their role as experts. It exists! ! ! Save it for later use when needed. The string is: ...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn