Get the data of each row from the CSV, and then their data cells in a variable

My CSV has a table like GIK65.png

Now, what I want to do, for each record I want to get the corresponding cell data and take them in variables. (Then I need to perform some tasks with variables).

eg. (for each row, their values ​​in variables)

$id = 1;
$name = 'Test';

etc.

You can use an array for this.

For example, $ row_1 = ('1', 'Test', 'chicago', 'testuser', '21', '123456789')

I tried google search, but the results were not relevant to my query.

+3
source share
5 answers

I applied my own technique by writing each separated comma.

0
source

, for .

<?php
    $row = 1;
    if (($handle = fopen("data.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            echo "<p> $num fields in line $row: <br /></p>\n";
            $row++;
            for ($c=0; $c < $num; $c++) {
                echo $data[$c] . "<br />\n";
               // echo $data[1];
            }
        }
        fclose($handle);
    }
    ?>

CSV

,

+2

doh... , JavaScript.

, PHP: http://codepad.org/8SBgTCYy

$labels = explode(",", "id,name,city,username,contact_id,phone");
$values = explode(",", "1,Test,chicage,testuser,21,123456789");

$i = 0;
$count = count($labels);
$object = array();
for ( ; $i < $count; $i++ ) {
    $object[$labels[$i]] = $values[$i];
}

var_dump($object);

: http://codepad.org/AmVp08QR

$values = explode(",", "id,1,name,Test,city,chicago,username,testuser,contact_id,21,phone,123456789");

$i = 0;
$count = count($values);
$object = array();

for( ; $i < $count; $i++ ) {
    $object[$values[$i]] = $values[$i+1];
}

var_dump($object);

:

id,name,city,username,contact_id,phone

1,Test,chicage,testuser,21,123456789

var labels = "id,name,city,username,contact_id,phone".split(","),
    values = "1,Test,chicage,testuser,21,123456789".split(","),

    object = {},
    i = 0,
    len = labels.length;

for( ; i < len; i++) object[labels[i]] = values[i];

object :

{
    id: "1",
    name: "Test",
    city: "chicago",
    username: "testuser",
    contact_id: "21",
    phone: "123456789"
} 

:

id,1,name,Test,city,chicago,username,testuser,contact_id,21,phone,123456789

var values = "id,1,name,Test,city,chicago,username,testuser,contact_id,21,phone,123456789".split(","),

    object = {},
    i = 0,
    len = values.length;

for ( ; i < len; i+=2 ) {
    object[values[i]] = values[i+1];
}

.

0

array_combine () can be useful here:

$labels = explode(",", "id,name,city,username,contact_id,phone"); 
$values = explode(",", "1,Test,chicage,testuser,21,123456789"); 
//  Use fgetcsv() to read these from your file

$data = array_combine($labels,$values);

var_dump($data);
0
source

All Articles