PHP CSV to Associative Array with Row Headings

岁酱吖の 提交于 2019-12-02 13:18:13

You need a second foreach to achieve what you want.

Something like this:

foreach ($all_rows as $row) {
    if($row) {
        foreach($row as $key => $val) {
            if($key == "Food" && $val == "Apples") {
                echo "Apples: " . "<br>";
                echo $row["In_Stock"] . "<br>";
                echo $row["On_order"] . "<br>";
            }
            else if($key == "Food" && $val == "Oranges") {
                echo "Oranges: " . "<br>";
                echo $row["In_Stock"] . "<br>";
                echo $row["On_order"] . "<br>";
            }
        }
    }
}

If you just want to print the values on your page, this could do it.

But I since you've mentioned to just call the values based on food type, you can create a function out of this.

Try this,

foreach ($all_rows as $key => $value) {
  echo $value['food'] . "\n";
  echo $value['In_Stock'] . "\n"

}

I think you are thinking to specifically. With your suggested requirement what would happen if you decide to sell potatoes. You would have to amend all your code.

What you need to change is the print loop.

So using this csv file

FOOD,IN_Stock,On_Order
Apples,1302,2304
Oranges,4356,335

You would get

$csv_file = 'file.csv';

$all_rows = array();

$header = null;//null; // has header
if (($handle = fopen($csv_file, "r")) !== FALSE) {
    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if ($header === null) {
            $header = $row;
            continue;
        }
        $all_rows[] = array_combine($header, $row);
    }

    fclose($handle);
}
print_r($all_rows);

foreach ($all_rows as $stock_item) {

    foreach ($stock_item as $key => $val){
        if ( $key == 'FOOD') {
            echo sprintf("\n%s", $val);
        } else {
            echo sprintf(' %s = %s', $key, $val);
        }

    }
}

The result would be

Apples IN_Stock = 1302 On_Order = 2304
Oranges IN_Stock = 4356 On_Order = 335

And if you then add Potatoes to the csv

FOOD,IN_Stock,On_Order
Apples,1302,2304
Oranges,4356,335
Potatoes,3333,999

With no changes to the code your output would be

Apples IN_Stock = 1302 On_Order = 2304
Oranges IN_Stock = 4356 On_Order = 335
Potatoes IN_Stock = 3333 On_Order = 999

Of course you may want to format the output differently.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!