Home  >  Article  >  Backend Development  >  PHP多维数组转一维数组的简单实现方法_php技巧

PHP多维数组转一维数组的简单实现方法_php技巧

WBOY
WBOYOriginal
2016-05-16 20:02:131619browse

本文实例讲述了PHP多维数组转一维数组的简单实现方法。分享给大家供大家参考,具体如下:

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] => !
)

希望本文所述对大家PHP程序设计有所帮助。

Statement:
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