循环遍历基于索引的PHP数组

时间:2015-01-10 18:33:46

标签: php arrays

如何使用索引为字符串数组赋值?让我们说我不知道​​数组中字符串的值是什么,所以我使用键代替。

可以是任何字符串列表的数组:

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

分配功能

$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];
                }
            }

如果我不提供其值,我该如何将值($ data [$ c])分配给相应的索引,而是使用数字索引?我知道我可以像这样访问数组,因为

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

但是当我运行我得到的功能时

0 => nameValue
1 => ageValue

而不是

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

1 个答案:

答案 0 :(得分:1)

您正在覆盖自己的数据:

 $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;

或者,您可以更新代码以跟踪所有值:

 $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];

 }