PHP CSV to Associative Array with Row Headings

前端 未结 3 685
我寻月下人不归
我寻月下人不归 2021-01-29 06:43

I have a CSV file with headings in both the columns and rows that i need as an associative array and the examples i have tried on SO haven\'t worked for me.

The closest

3条回答
  •  面向向阳花
    2021-01-29 07:05

    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.

提交回复
热议问题