Define 2D array with loops in php

后端 未结 2 1709
闹比i
闹比i 2021-01-15 03:57

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 e

2条回答
  •  清酒与你
    2021-01-15 04:54

    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.

提交回复
热议问题