-1

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 example i found was CSV to Associative Array but i couldn't print the data, so i must be missing something.

Any help would be appreciated

$all_rows = array();

$header = 1;//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);
}


// CSV Example
// [FOOD][IN_Stock][On_Order]
// [Apples][1302][2304]
// [Oranges][4356][335]


foreach ($all_rows as $key => $value) {

    // This prints ok based on the row number
    echo $all_rows[$key]['Instock'];

    // But i need to be able to call data based on the Food Type
    echo $all_rows['Apples']['In_Stock'];
    echo $all_rows['Apples']['On_order'];
    echo $all_rows['Oranges']['In_Stock'];
    echo $all_rows['Oranges']['On_order'];

}

I can print the data by calling the row number, but the data will not always be the same and therefore need to print based on the headers in the first column.

Added the printed Array as Requested:

Array
(
[0] => Array
    (
        [Food] => Apples
        [In_Stock] => 6329
        [On_Order] => 375
    )

[1] => Array
    (
        [Food] => Pears
        [In_Stock] => 3329
        [On_Order] => 275
    )

[2] => Array
    (
        [Food] => Oranges
        [In_Stock] => 629
        [On_Order] => 170
    )
  ) 

Encase anyone else needs it, this is what i used:

$csv = array();
foreach ($all_rows as $row) {
if($row) {
    foreach($row as $key => $val) {

        $csv[$val]['In_Stock'] = $row["In_Stock"];
        $csv[$val]['On_order'] = $row["On_order"];

    }
}
}
3
  • 1
    show print_r($all_rows) here Commented May 13, 2017 at 15:33
  • print_r($header) Commented May 13, 2017 at 15:40
  • Array ( [0] => Food [1] => In_Stock [2] => On_Order ) Commented May 13, 2017 at 15:48

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This got me close, just modified it a bit to populate all "foods": $csv = array(); foreach ($all_rows as $row) { if($row) { foreach($row as $key => $val) { $csv[$val]['In_Stock'] = $row["In_Stock"]; $csv[$val]['On_order'] = $row["On_order"]; } } }
@JamesParry Cool! Glad it helped!
0

Try this,

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

}

1 Comment

Why should the OP "try this code"? A good answer will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO that may find this question and be reading your answer.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.