Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've seen numerous examples on how to take a CSV file and then create an associative array with the headers as the keys.

For example:

Brand,Model,Part,Test
Honda,Civic,123,244
Honda,Civic,135,434
Toyota,Supra,511,664

Where it would create an Array such as Array[$num][$key] where $key would be Brand, Model, Part, Test.

So If I wanted to access the test value "434" I would have to loop every index in the array and then ignore any Brands that were not honda, and any models that were not Civic


What I need to do is access the value most directly, instead of running through a for loop going through each $num index. I want to be able to access the value test "434" with:

Array['Honda']['Civic']['135']

or control a for statement with looping through every model Honda has... something like

foreach $model in Array['Honda']

At the very least I need to be able to go through every model given a known Brand and access all the relative info for each.

Edit:

Just to confirm I was setting this up an example. My actually data has headers like:

brand model part price shipping description footnote

Of which I need to access all the information tied to the part (price, shipping,desc, footnote)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
269 views
Welcome To Ask or Share your Answers For Others

1 Answer

Too many long solutions. I've always found this to be the simplest:

<?php
    /* Map Rows and Loop Through Them */
    $rows   = array_map('str_getcsv', file('file.csv'));
    $header = array_shift($rows);
    $csv    = array();
    foreach($rows as $row) {
        $csv[] = array_combine($header, $row);
    }
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...