>  기사  >  백엔드 개발  >  PHP怎么将多维数组转换为二维数组?

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

PHPz
PHPz원래의
2016-06-13 12:05:103132검색

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中文网!!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.