简体   繁体   中英

PHP changing the index of multidimentional array to value of variable

Pretty new to PHP. I have a csv feed that i am trying to display every line of in the right place. The feed is loaded into a multidimentional array and I can echo out specific places like this.

echo $readcsv[0][2]

But I am trying to use the value of the variable $row in stead of the first number while doing a while loop.

Something like:

echo $readcsv[$row][2]

I have tried next(), str_replace() and strtr() but none of them seems to work while the loop is running.

$row = 1;
$readcsv = array(); 

if (($handle = fopen("file.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
        $num = count($data);

        echo $readcsv[$row][2];

        $row++;
        for ($c=0; $c < $num; $c++) {
        }
        $mycsvfile[] = $data; 
    }
    fclose($handle);
}

CSV file:

title;image_link;link;empty;price;
1;back.gif;http://link.com;;19.95;
2;back.gif;http://link.com;;19.95;
3;back.gif;http://link.com;;19.95;
4;back.gif;http://link.com;;19.95;
5;back.gif;http://link.com;;19.95;

I am not quite sure from your code and question exactly what you are trying to do, but maybe its something like this

if (($handle = fopen("file.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {

        // you load the line into $data and its a one dimentional array
        // occurance 2 is the `link` (http://link.com) if that what you want to echo
        echo $data[2];

        // as you have a loop, maybe you were trying to
        // echo each fields from the csv so you can do that like this
        foreach ($data as $idx => $value) {

            echo "Column $idx = $value";
        }
        $mycsvfile[] = $data;
    }
    fclose($handle);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM