Home >Backend Development >PHP Problem >How to increase the dimensions of an array in php

How to increase the dimensions of an array in php

青灯夜游
青灯夜游Original
2022-05-26 18:49:361952browse

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.

How to increase the dimensions of an array in php

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);
?>

How to increase the dimensions of an array in php

Example 2: Convert two-dimensional array to three-dimensional array

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$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));
?>

How to increase the dimensions of an array in php

How to increase the dimensions of an array in php

##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(&#39;content-type:text/html;charset=utf-8&#39;);   
$a = [1,&#39;2&#39;=>2,&#39;a&#39;=>&#39;a&#39;,&#39;b&#39;=>&#39;b&#39;];
$b = [&#39;a&#39;=>&#39;a&#39;,&#39;b&#39;=>&#39;d&#39;];
$c = array_merge_recursive($a,$b);
var_dump($c);
?>

How to increase the dimensions of an array in php

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!

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