Home  >  Article  >  Backend Development  >  Put values ​​into two-dimensional array in PHP loop

Put values ​​into two-dimensional array in PHP loop

不言
不言Original
2018-04-24 10:10:151328browse

The content of this article is to put values ​​into a two-dimensional array in a PHP loop. It has a certain reference value. Now I share it with you. Friends in need can refer to it

1. Define a Array, put the value into the two-dimensional array

$a = [];$b = ['a','b','c','d'];foreach($b as $v){    $a['a'][] = $v;
}

In this way, printing this $a will get a two-dimensional array, but when using the following code, $a will get It can only get one value,

instead of putting all the values ​​in $b into $a['a']this array

$b = ['a','b','c','d'];foreach($b as $v){    $a = [];    $a['a'][] = $v;
}

At the same time, in While loops and for loops are the same, when defining an array, it must be placed outside the loop, otherwise

can only put the value of the last loop into this array

Explanation: Each loop $a is redefined once, so this phenomenon will occur.

Related recommendations:

In-depth understanding of php loop statements

The above is the detailed content of Put values ​​into two-dimensional array in PHP loop. 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