php把多维数组变为一维数组的方法

第一种方法,使用php自带的函数:array_walk_recursive:

$colum = [[1, 2, 3], [4, 5, 6], [7, 8, 9=>['a','b'=>['c','d']]]];
 $arr = reduce($colum);
  var_dump($arr);
  function reduce($array) {
      $return = [];
      array_walk_recursive($array, function ($x,$index) use (&$return) {
          $return[] = $x;
      });
      return $return;
  }
结果:
array:11 [
  0 => 1
  1 => 2
  2 => 3
  3 => 4
  4 => 5
  5 => 6
  6 => 7
  7 => 8
  8 => "a"
  9 => "c"
  10 => "d"
]

第二种方法使用递归:

$colum = [[1, 2, 3], [4, 5, 6], [7, 8, 9=>['a','b'=>['c','d']]]];
 $arr = he($colum);
  var_dump($arr);
 public function he($arr,&$data){
        if (is_array($arr)){
            foreach($arr as $v){
                if (is_array($v)){
                    $this->he($v,$data);
                } else{
                    $data[] = $v;
                }
            }
        }else{
            $data[] = $arr;
        }
    }
结果:
array:11 [
  0 => 1
  1 => 2
  2 => 3
  3 => 4
  4 => 5
  5 => 6
  6 => 7
  7 => 8
  8 => "a"
  9 => "c"
  10 => "d"
]

你可能感兴趣的:(PHP)