Home > Article > Backend Development > How to convert one-dimensional array to two-dimensional array in php
In PHP, you can use the array_chunk() function to convert a one-dimensional array into a two-dimensional array. The function of this function is to split the array. It can split an array into multiple array blocks; the syntax format is "array_chunk ($arr,count($arr)/2)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
In php, you can use array_chunk () function to convert a one-dimensional array into a two-dimensional array.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $arr=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel"); echo "原一维数组:"; var_dump($arr); $chunk=array_chunk($arr,count($arr)/2); echo "将一维数组转为二维数组:"; var_dump($chunk); ?>
Explanation:
array_chunk() function can To split an array into multiple array blocks, the syntax is as follows:
array array_chunk ( array $arr , int $size [, bool $preserve_keys = false ] )
Parameter description:
arr represents the array to be split;
size represents the number of elements of the divided sub-array;
preserve_keys represents whether to retain the original key names in the arr array. The default is false, that is, not retained, split Each subsequent sub-array will use a new numeric index starting from 0; if set to true, the original key names in arr will be retained.
array_chunk() will split the arr array into multiple sub-arrays, and the number of elements in each sub-array is determined by size. The last subarray may have less than size elements.
Return value: Returns a multi-dimensional array composed of divided sub-arrays.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert one-dimensional array to two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!