The previous two articles, "PHP one-dimensional array" and "PHP two-dimensional array", detail one-dimensional arrays and two-dimensional arrays. in this chapter, I will introduce the mutual conversion between one-dimensional arrays and two-dimensional arrays! The previous two articles, "What is a one-dimensional php array, a one-dimensional php array instance explanation" and "What is a two-dimensional php array, php two-dimensional array example describes in detail the one-dimensional array and two-dimensional array, this chapter I will introduce the implementation of mutual conversion between one-dimensional array and two-dimensional array!
Let's not talk about it. First, we will introduce the sample code for converting a one-dimensional array into a two-dimensional array:
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 ))
Two ways to convert a two-dimensional array into a one-dimensional array:
How to convert the following two-dimensional array into one-dimensional array.
'45', 'name'=>'jack' ), array( 'id'=>'34', 'name'=>'mary' ), array( 'id'=>'78', 'name'=>'lili' ),);?>
Method 1:
foreach($msg as $k => $v){ $ids[] = $id; $names[] = $name; }
Method 2:
$ids = array_column($msg, 'id');$names = array_column($msg, 'name');
The result of the preceding two solutions: print_r ($ names:
Array( [0]=>jack [1]=>mary [2]=>lili)
Note: array_column (); there can be a third parameter, such as $ n = array_column ($ msg, 'name', 'id ');
The result of print_r ($ n); is:
Array( [45]=>jack [34]=>mary [78]=>lili)
[Recommended tutorials]
1. related topic recommendations: php Array (Array)
2. related video course recommendations: sort multiple arrays at the same time. multi-dimensional arrays are converted into one-dimensional arrays by values: array_multisort ()
The above is a detailed example of mutual conversion between one-dimensional arrays and two-dimensional arrays in PHP. For more information, see other related articles in the first PHP community!