Home > php教程 > php手册 > php一维数据转多维

php一维数据转多维

WBOY
Release: 2016-06-21 08:48:18
Original
1762 people have browsed it

今天在论坛里看到有个朋友的需求,见证csdn的版主都不愧是大牛的角色存在啊!!!保存起来,方便以后需要的时候使用。


字符串为:

vcD4KPHByZSBjbGFzcz0="brush:java;">1 = 光电鼠标 2 = 机械鼠标 3 = 没有鼠标 1.1 = 黑色光电鼠标 1.2 = 红色光电鼠标 1.2.1 = 蓝牙红色光电鼠标
版主解答为:

<?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);
?>
Copy after login

打印出来的数组为:
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
                (
                )
 
        )
 
)
Copy after login
看到这些评论我笑啦:







Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template