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

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

韦小宝
Release: 2023-03-19 20:26:01
Original
1776 people have browsed it

The following editor will share with you an article about PHP applicationforeachMagic conversionArray(Explanation with examples), which is a good reference for learning PHP value, I hope it will be helpful to everyone. Friends who are interested in PHP, please follow the editor to have a look

Requirements:

Convert two-dimensional array$arr ​​is converted 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',
   ),
  );
Copy after login

Conversion:

foreach ($arr as $key => $value) {
 $change[$value['time']][$value['type']] = $value['data'];
}
Copy after login

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)
 }
}
Copy after login

The above This article on PHP using foreach to magically convert arrays (explanation with examples) is all the content that the editor has shared with you. I hope it can give you a reference! !

Related recommendations:

#Examples of combining and deduplicating php numbers

Several kinds of deletions Method for specifying value elements in php array

php array replacement function array_replace()

php array to string method to obtain the path represented by the array analyze

The above is the detailed content of PHP uses foreach to magically convert arrays (explanation with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template