欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2024-02-04 10:10:58
...
PHP怎么将多维数组转换为二维数组?

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

<?php
$a = array(
  0=>array(
    'categoryid'=>1,
    'name'=>"AA1",
    'parent'=>0,
    'childs'=>array(
      0=>array(
        'categoryid'=>2,
        'name'=>"BB1",
        'parent'=>1,
        'childs'=>array(
          0=>array(
            'categoryid'=>3,
            'name'=>"CC",
            'parent'=>2,
            'childs'=>array(
              0=>array(
                'categoryid'=>4,
                'name'=>"dd1",
                'parent'=>3,
              ),
              1=>array(
                'categoryid'=>5,
                'name'=>"dd2",
                'parent'=>3,
              ),
            ),
          ),
        ),
      ),
      1=>array(
        'categoryid'=>6,
        'name'=>"BB2",
        'parent'=>1,
      ),
    ),
  ),
  1=>array(
    'categoryid'=>7,
    'name'=>"AA2",
    'parent'=>0,
  )
);
function imp($tree, $children='childs') {
  $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)
      'categoryid' => int 1
      'name' => string 'AA1' (length=3)
      'parent' => int 0
  1 => 
    array (size=3)
      'categoryid' => int 2
      'name' => string 'BB1' (length=3)
      'parent' => int 1
  2 => 
    array (size=3)
      'categoryid' => int 3
      'name' => string 'CC' (length=2)
      'parent' => int 2
  3 => 
    array (size=3)
      'categoryid' => int 4
      'name' => string 'dd1' (length=3)
      'parent' => int 3
  4 => 
    array (size=3)
      'categoryid' => int 5
      'name' => string 'dd2' (length=3)
      'parent' => int 3
  5 => 
    array (size=3)
      'categoryid' => int 6
      'name' => string 'BB2' (length=3)
      'parent' => int 1
  6 => 
    array (size=3)
      'categoryid' => int 7
      'name' => string 'AA2' (length=3)
      'parent' => int 0

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

相关标签: PHP 数组