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

WBOY
Release: 2016-05-16 20:02:13
Original
1586 people have browsed it

本文实例讲述了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;
}

Copy after login

执行后的效果:

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

Copy after login

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

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!