Home >Backend Development >PHP Tutorial >Detailed explanation of the steps to convert an array using foreach in PHP
This time I will bring you PHP usageforeachconversionarraydetailed steps, what are the precautions for using foreach in PHP to convert arrays, the following is a practical case , let’s take a look.
Requirements:
Convert two-dimensional array$arr to 'time' and 'type' Standard, 'data' is a two-dimensional array of values;
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) } }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to php Chinese Other related articles online!
Recommended reading:
Detailed explanation of the steps to implement regular expression group capture in PHP
Detailed explanation of the steps to use mb_strpos in PHP
The above is the detailed content of Detailed explanation of the steps to convert an array using foreach in PHP. For more information, please follow other related articles on the PHP Chinese website!