Simple implementation method of converting multi-dimensional array to one-dimensional array in PHP

PHP中文网
Release: 2023-02-28 22:24:02
Original
2177 people have browsed it

The example in this article describes the simple implementation method of converting a multi-dimensional array to a one-dimensional array in PHP. Share it with everyone for your reference, the details are as follows:

The PHP language itself does not have a function to convert multi-dimensional arrays into one-dimensional arrays, but we can write a PHP function ourselves to achieve the function of converting multi-dimensional arrays into one-dimensional arrays.

Using recursion, it is simple and crude. The entire function body implements this function in 9 lines of code. The PHP source code is as follows:

$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

The effect after execution:

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

I hope this article will be helpful to everyone PHP programming helps.

The above introduces the simple implementation method of converting multi-dimensional arrays to one-dimensional arrays in PHP, including all aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

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