Home > php教程 > PHP源码 > php多维数组转一维数组的函数

php多维数组转一维数组的函数

WBOY
Release: 2016-06-08 17:19:51
Original
1122 people have browsed it

php多维数组转一维数组我们用到最多的就是直接foreach了,但是如何使用php函数来实现呢,下面我们就一起来看看吧.

<script>ec(2);</script>

php语言本身没有将多维数组转为一维数组的函数,但是我们可以自己写一个php函数来实现将多维转一维的功能。

运用了递归,简单粗暴,整个函数体9行代码就实现了该功能,php源码如下:

$multi = array(
 array(
  array(
   'wo',
   'shi'
  ),
  'php'
 ),
 'cheng',
 array(
  array(
   'xu',
   'yuan',
  )
 ),
 '!'
);
$multi = arrToOne($multi);
print_r($multi);

function arrToOne($multi) {
 $arr = array();
 foreach ($multi as $key => $val) {
  if( is_array($val) ) {
   $arr = array_merge($arr, arrToOne($val));
  } else {
   $arr[] = $val;
  }
 }
 return $arr;
}

执行后的效果:

Array
(
    [0] => wo
    [1] => shi
    [2] => php
    [3] => cheng
    [4] => xu
    [5] => yuan
    [6] => !
)

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