Home >Backend Development >PHP Problem >How to increase the dimensions of an array in php
Two methods: 1. Use array_chunk() to divide the array into new array chunks (sub-arrays), the syntax is "array_chunk(array, number of sub-array elements)". 2. Use array_merge_recursive() to merge an array with the same key name. The values of the same key will be merged into a sub-array.
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
php increases the two dimensions of the array Method
Method 1: Use array_chunk() function
array_chunk() function splits an array into new array chunks.
Use this function to divide the array at each level of the specified array (fractal dimension) and then convert it into a higher-dimensional array.
Example 1: Convert one-dimensional array to two-dimensional array
<?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); ?>
Example 2: Convert two-dimensional array to three-dimensional array
<?php header('content-type:text/html;charset=utf-8'); $arr= array ( array("张三",25,"男"), array("李四",21,"男"), array("娜娜",22,"女"), array("张三",25,"男"), array("李四",21,"男"), array("娜娜",22,"女") ); echo "原二维数组:"; var_dump($arr); echo "将二维数组转为三维数组:"; var_dump(array_chunk($arr,2)); ?>
##Method 2: Use the array_merge_recursive() function
Use the array_merge_recursive() function to merge a Arrays with the same key name. Merge arrays, when encountering the same key, merge the values in the key into a sub-array<?php header('content-type:text/html;charset=utf-8'); $a = [1,'2'=>2,'a'=>'a','b'=>'b']; $b = ['a'=>'a','b'=>'d']; $c = array_merge_recursive($a,$b); var_dump($c); ?>Recommended learning: "
PHP Video Tutorial 》
The above is the detailed content of How to increase the dimensions of an array in php. For more information, please follow other related articles on the PHP Chinese website!