views:

55

answers:

2

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])));  
}
+4  A: 
$rowData = array();
foreach($rows as $value) {
  $rowData[] = explode("\t", $value);
}
Emil Vikström
That worked, thank you so much!
Michael
+2  A: 
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.

Hammerite
Thank you for that explanation, I foolishly didn't realize I was even calling an array() function. Very informative!
Michael