PHP CSV to Associative Array with Row Headings

前端 未结 3 675
我寻月下人不归
我寻月下人不归 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 06:59

    Try this,

    foreach ($all_rows as $key => $value) {
      echo $value['food'] . "\n";
      echo $value['In_Stock'] . "\n"
    
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-29 07:08

    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.

    0 讨论(0)
提交回复
热议问题