0

im been looking in to php array_column and array_map but i still dont get it!.

This is the code i use for loading my CSV

    <?PHP
        $row = 1;
        $faq = array(); //define the main array.

        if (($handle = fopen("file.csv", "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                $num = count($data);
                $row++;

                for ($c = 0; $c < $num; $c++) {
                }
                $faq[] = $data; //add the row to the main array.
            }

            fclose($handle);
        }
    ?>

And this is is how i output the data:

echo $faq[1][13];

So the [1] is the row and the [13] is the column.

But if that info is not longer on the row [1] but i still want to finds that data. So if we say column and row 0 is a ID/header and i could write

echo $faq['printing']['Hash_tag'];

['printing'] = would mean the row it finds that word on column 0

['Hash_tag'] = would mean the column "13" where it finds that on the top row.

For sure this is a duplicate but i been looking in to this for a long time and im almost giving up as i cant figure it out.

2
  • something is wrong in this code. There is a for block that does nothing. Please check that Commented Dec 11, 2017 at 13:46
  • It works! In the way i already specified! Without "index" of the first row/column. Commented Dec 11, 2017 at 13:51

1 Answer 1

1

I've written a very small template - there is no error checking (as in your code) so please add it as you see fit...

$fh = fopen("a.txt", "r");
$header = fgetcsv($fh);
$faq = [];
while ( $data = fgetcsv($fh))   {
    $faq [ $data[0] ] = array_combine($header, $data);
}

print_r($faq);

Run with the file

tag1,tag2
a,1
b,2
r,t

Gives the output

Array
(
    [a] => Array
        (
            [tag1] => a
            [tag2] => 1
        )

    [b] => Array
        (
            [tag1] => b
            [tag2] => 2
        )

    [r] => Array
        (
            [tag1] => r
            [tag2] => t
        )

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

9 Comments

echo $faq['tag1']['a']; still dont show A, or im i writing something wrong?
I would have thought you wanted $faq['a']['tag1'] - as 'a' is the value in column 0 and 'tag1' was the label in the first row for the first column. Or I may have got it the wrong way round.
maybe i wrote it wrong i tried both ways.. And i still dont get the any output
What does the print_r give? This should show the output as I gave and with that - echo $faq['a']['tag1']; gives a.
That's most likely a JSON file.
|

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.