Home >Backend Development >PHP Tutorial >Example of converting one-dimensional array to two-dimensional array in PHP
The previous two articles "What is a php one-dimensional array, a detailed explanation of a php one-dimensional array example" and "What is a php two-dimensional array, a detailed explanation of a php two-dimensional array example 》Introducing one-dimensional arrays and two-dimensional arrays in detail. In this chapter, I will introduce the implementation of mutual conversion between one-dimensional arrays and two-dimensional arrays!
Without further ado, let’s first introduce the sample code for converting a one-dimensional array into a two-dimensional array:
<?php header("Content-Type:text/html; charset=utf-8"); $asr[1] = array("a","b","c","d"); $asr[2] = array("a","b","c","d"); $asr[3] = array("a","b","c","d"); $newarray = array(); foreach($asr as $a) { $newarray[] = $a; } print_r($newarray); ?>
The output result is:
Array ( [0] => Array ( [0] => a [1] => b [2] => c [3] => d ) [1] => Array ( [0] => a [1] => b [2] => c [3] => d ) [2] => Array ( [0] => a [1] => b [2] => c [3] => d ) )
2 ways to convert a two-dimensional array into a one-dimensional array:
How to convert the following two-dimensional array into a one-dimensional array.
<?php header("Content-Type:text/html; charset=utf-8"); $msg = array( array( 'id'=>'45', 'name'=>'jack' ), array( 'id'=>'34', 'name'=>'mary' ), array( 'id'=>'78', 'name'=>'lili' ), ); ?>
The first method:
foreach($msg as $k => $v){ $ids[] = $id; $names[] = $name; }
The second method:
$ids = array_column($msg, 'id'); $names = array_column($msg, 'name');
The result of the above two solutions print_r($names); is:
Array( [0]=>jack [1]=>mary [2]=>lili )
Note: array_column(); can have a third parameter, such as $n = array_column($msg, 'name', 'id');
print_r($n);The result is:
Array( [45]=>jack [34]=>mary [78]=>lili )
【Related tutorial recommendations】
1. Relevant topic recommendations: "php array (Array)"
2 . Related video course recommendations: " Sort multiple arrays at the same time. Multidimensional arrays are first converted into one-dimensional arrays by value: array_multisort()"
The above is the detailed content of Example of converting one-dimensional array to two-dimensional array in PHP. For more information, please follow other related articles on the PHP Chinese website!