Home>Article>Backend Development> Detailed explanation of the steps to convert an array using foreach in PHP

Detailed explanation of the steps to convert an array using foreach in PHP

php中世界最好的语言
php中世界最好的语言 Original
2018-05-19 11:42:40 1916browse

This time I will bring you PHP usageforeachconversionarraydetailed steps, what are theprecautionsfor using foreach in PHP to convert arrays, the following is a practical case , let’s take a look.

Requirements:

Converttwo-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!

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