phpexcelphpexcelreader

Loop through Object in PHP


I am trying to read each element of an Object array, the code reads values from an excel file and then assign the values to a variable.

for ($row = 1; $row <= $highestRow; ++ $row) {

    $fname = $worksheet->getCellByColumnAndRow(0, $row);

    echo '<td>' . $fname . '<br></td>';
}

The output of 'fname' is four different names, however I want to read each value using a loop and then assign them to a link as follows: www.example.com/fname so that four different links get opened up when I execute the code. I just can't figure out how to access each element of 'fname' object one by one. I read over examples available online, but to no avail. Please bear in mind I am a newbie to PHP. Thanks


Solution

  • If $fname contains a space delimited list of names like Tim John Sam Tom then you can use explode() to turn that STRING into an array of strings.

    for ($row = 1; $row <= $highestRow; ++ $row) {
    
        $fname = $worksheet->getCellByColumnAndRow(0, $row);
        $names = explode(' ', $fname);
        foreach ( $names as $name ) {
            echo '<td>' . $name . '</td>';
        }
    }
    

    So if you use the $names array

    $names[0] would be `Tim`
    $names[1] would be `John`
    $names[2] would be `Sam`
    $names[3] would be `Tom`