Home  >  Article  >  Backend Development  >  PHP uses foreach to magically convert arrays (explanation with examples) php examples

PHP uses foreach to magically convert arrays (explanation with examples) php examples

jacklove
jackloveOriginal
2018-06-28 17:41:211214browse

The editor below will share with you an article about the magical conversion of arrays using foreach in PHP (explanation with examples). It has a good reference value and I hope it will be helpful to everyone. Let's follow the editor and take a look.

Requirements:

Convert the two-dimensional array $arr to 'time' and 'type' is the subscript and 'data' is the two-dimensional array of 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)
 }
}

The above article on PHP using foreach to magically convert arrays (explanation with examples) is all the content shared by the editor. I hope it can give you a For reference, I also hope that everyone will support the php Chinese website.

Articles you may be interested in:

Solution to the error when accessing array elements in PHP double quotes php tips

php How to delete a certain value element in a one-dimensional array php skills

PHP implements the inverse color processing function of images php skills

The above is the detailed content of PHP uses foreach to magically convert arrays (explanation with examples) php examples. 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