Home > Article > Backend Development > How to use foreach to convert an array in PHP
This article mainly shares with you an article about the magical conversion array of PHP using foreach (explanation with examples). It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.
Requirements:
Convert the two-dimensional array $arr into a two-dimensional array with 'time' and 'type' as subscripts and 'data' as the value;
Original array:
$arr = array( 0 => array( 'data' => 100, 'type' => 1, 'time' => '2018-01-26', ), 1 => array( 'data' => 200, 'type' => 2, 'time' => '2018-01-26', ), 2 => array( 'data' => 300, 'type' => 2, 'time' => '2018-01-27', ), 3 => array( 'data' => 400, 'type' => 3, 'time' => '2018-01-27', ), 4 => array( 'data' => 500, 'type' => 4, 'time' => '2018-01-28', ), );
Conversion:
foreach ($arr as $key => $value) { $change[$value['time']][$value['type']] = $value['data']; }
Result:
array(3) { ["2018-01-26"] => array(2) { [1] => int(100) [2] => int(200) } ["2018-01-27"] => array(2) { [2] => int(300) [3] => int(400) } ["2018-01-28"] => array(1) { [4] => int(500) } }
Related recommendations:
foreach and A brief introduction to each
Analysis of PHP loop statements—while, for, foreach, do while
For and foreach traverse arrays in PHP Detailed explanation of the difference
The above is the detailed content of How to use foreach to convert an array in PHP. For more information, please follow other related articles on the PHP Chinese website!