PHP怎么将多维数组转换为二维数组?

PHPz
发布: 2020-09-05 14:21:18
原创
3155 人浏览过

PHP怎么将多维数组转换为二维数组?

PHP将多维数组转换为二维数组的方法:

<?php
$a = array(
  0=>array(
    &#39;categoryid&#39;=>1,
    &#39;name&#39;=>"AA1",
    &#39;parent&#39;=>0,
    &#39;childs&#39;=>array(
      0=>array(
        &#39;categoryid&#39;=>2,
        &#39;name&#39;=>"BB1",
        &#39;parent&#39;=>1,
        &#39;childs&#39;=>array(
          0=>array(
            &#39;categoryid&#39;=>3,
            &#39;name&#39;=>"CC",
            &#39;parent&#39;=>2,
            &#39;childs&#39;=>array(
              0=>array(
                &#39;categoryid&#39;=>4,
                &#39;name&#39;=>"dd1",
                &#39;parent&#39;=>3,
              ),
              1=>array(
                &#39;categoryid&#39;=>5,
                &#39;name&#39;=>"dd2",
                &#39;parent&#39;=>3,
              ),
            ),
          ),
        ),
      ),
      1=>array(
        &#39;categoryid&#39;=>6,
        &#39;name&#39;=>"BB2",
        &#39;parent&#39;=>1,
      ),
    ),
  ),
  1=>array(
    &#39;categoryid&#39;=>7,
    &#39;name&#39;=>"AA2",
    &#39;parent&#39;=>0,
  )
);
function imp($tree, $children=&#39;childs&#39;) {
  $imparr = array();
  foreach($tree as $w) {
    if(isset($w[$children])) {
      $t = $w[$children];
      unset($w[$children]);
      $imparr[] = $w;
      if(is_array($t)) $imparr = array_merge($imparr, imp($t, $children));
    } else {
      $imparr[] = $w;
    }
  }
  return $imparr;
}
var_dump(imp($a));
?>
登录后复制

输出:

array (size=7)
  0 => 
    array (size=3)
      &#39;categoryid&#39; => int 1
      &#39;name&#39; => string &#39;AA1&#39; (length=3)
      &#39;parent&#39; => int 0
  1 => 
    array (size=3)
      &#39;categoryid&#39; => int 2
      &#39;name&#39; => string &#39;BB1&#39; (length=3)
      &#39;parent&#39; => int 1
  2 => 
    array (size=3)
      &#39;categoryid&#39; => int 3
      &#39;name&#39; => string &#39;CC&#39; (length=2)
      &#39;parent&#39; => int 2
  3 => 
    array (size=3)
      &#39;categoryid&#39; => int 4
      &#39;name&#39; => string &#39;dd1&#39; (length=3)
      &#39;parent&#39; => int 3
  4 => 
    array (size=3)
      &#39;categoryid&#39; => int 5
      &#39;name&#39; => string &#39;dd2&#39; (length=3)
      &#39;parent&#39; => int 3
  5 => 
    array (size=3)
      &#39;categoryid&#39; => int 6
      &#39;name&#39; => string &#39;BB2&#39; (length=3)
      &#39;parent&#39; => int 1
  6 => 
    array (size=3)
      &#39;categoryid&#39; => int 7
      &#39;name&#39; => string &#39;AA2&#39; (length=3)
      &#39;parent&#39; => int 0
登录后复制

更多相关知识,请访问 PHP中文网!!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板