在PHP中的foreach循环中存储数组数据

I am wondering how can I store all values from a foreach loop, I know that I am re-initialising in the loop but I'm not sure how to store the data. Heres my basic loop:

$array = array("v1", "v2", "v3", "v4");
foreach($array as $row){
    $arr = array('val' => $row);
    echo $row;
}
print_r($arr);

So when I use the print_r($arr) the only thing outputted would be v4 and I know that the values are there because the echo $row; does return each output individually.

My question would be how can I store each instance of row in my array?

Create a new array, fill it:

$array = array("v1", "v2", "v3", "v4");

$newArray = array();

foreach($array as $row){
    // notice the brackets
    $newArray[] = array('val' => $row);

}

print_r($newArray);

It looks like you are storing your array wrong.

Try adjusting the $arr = array('val' => $row);

to:

$arr[] = array('val' => $row);

This will set it so you pick up each line as a separate array which you can easily navigate through.

Hope this helps!

If I'm reading correctly, you want to transform your array from simple values to key-value pairs of 'val'->number. array_map is a concise way of doing this sort of transformation.

$array = array("v1", "v2", "v3", "v4");
$arr = array_map(function($v) { return array('val'=>$v); }, $array);
print_r($arr);

While it doesn't matter in this case, array_map also has the handy feature of preserving your keys, in case that is desired.

Note that you can also provide a named function to array_map, instead of providing the implementation inline, which can be nice in the event that your transform method gets more complicated. More on array_map here.