user3822370
user3822370

Reputation: 647

Loop through PHP array based on index

How can I assign values to an array of strings using an index? Let's say I don't know what the values of the strings are in the array, so I use keys instead.

Array that could be any list of strings:

$this->cols = array(
    'name',
    'age'
);

assignment function

$row = 1;
        if (($f = fopen($this->file['tmp_name'], "r")) !== FALSE) {
          while (($data = fgetcsv($f, 0, ",")) !== FALSE) {
                $num = count($data);
                $row++;
                for ($c=0; $c < $num; $c++) {
                    $colName = $this->cols[$c];
                    $this->cols[$colName] = $data[$c];
                }
            }

How can I assign the value ($data[$c]) to the corresponding index if I don't supply its value, but rather use a numerical index? I know for a fact that I can access the array like this because

$colName[0] = 'name'
$colName[1] = 'age'

But when I run the function I get

0 => nameValue
1 => ageValue

Instead of

'name' => nameValue
'age' => ageValue

Upvotes: 1

Views: 74

Answers (1)

cwallenpoole
cwallenpoole

Reputation: 82028

You're overwriting your own data:

 $num = count($data);
 $row++;
 for ($c=0; $c < $num; $c++) {
     // every row of the CSV will update the same keys
     $colName = $this->cols[$c];
     $this->cols[$colName] = $data[$c];

 }

 // I suggest adding a `break` after that for look to see the problem.
 break;

Alternatively, you could update the code to track all values:

 $num = count($data);
 $row_val = array();
 $this->cols[] = $row_val;
 $row++;
 for ($c=0; $c < $num; $c++) {
     // every row of the CSV will update the same keys
     $colName = $this->col_names[$c];
     $row_val[$colName] = $data[$c];

 }

Upvotes: 1

Related Questions