Put values into a 2d array in a loop

1. Define an array and put the values ​​into a two-dimensional array

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

Printing this like this $awill get a two-dimensional array, but when using the following code, $ait 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 the while loop, the for loop is the same as when the array is defined, it must be placed outside the loop, otherwise

Only the value of the last loop can be put into this array

Explanation: It is redefined every time the loop is $arepeated, so it will cause this phenomenon to happen.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324741315&siteId=291194637