Define 2D array with loops in php
I have an array $rows
where each element is a row of 15 tab-delimited开发者_开发问答 values. I want to explode $rows
into a 2D array $rowData
where each row is an array element and each tab-delimited value is assigned to a different array element. I've tried these two methods without success. I know the first one has a coding error but I do not know how to correct it. Any help would be amazing.
for ($i=0; $i<count($rows); $i++){
for ($j=0; $j<15; $j++){
$rowData = array([$i] => array (explode(" ", $rows[$j])));
}
}
foreach ($rows as $value){
$rowData = array( array (explode(" ", $rows[$value])));
}
$rowData = array();
foreach($rows as $value) {
$rowData[] = explode("\t", $value);
}
for ($j=0; $j<15; $j++) {
$rowData[$j] = explode("\t", $rows[$j]);
}
To expand: The problem with the following code:
$rowData = array([$i] => array (explode(" ", $rows[$j])));
is that you don't appear to know what the different things you've written mean precisely.
A call to array() returns a new array with the indicated elements. So array (explode(" ", $rows[$j]))
yields an array with a single element, namely the array returned by explode()
. And you're wrapping that in another call to array()
, specifying the loop variable $i
as the key corresponding to that element. Also, you're using the assignment symbol =
, which means that every time you go through the loop, $rowData
is being completely overwritten - what you wanted was to add new elements to it without getting rid of the old ones.
精彩评论