0

我正在使用 WP Alchemy 创建一个带有多个复选框的元框。

我遇到的麻烦是,我有一个学术课程的 csv 列表,我想从中创建复选框选项。所以我把 csv 变成了一个数组,盒子是由这个数组组成的。但是,使用我现在拥有的代码,仅在数组中创建了最后一行。

<?php

$file_handle = fopen('curriculum.csv', 'r');

while (!feof($file_handle) ) {

$line_of_text = fgets($file_handle);
$parts = explode(',', $line_of_text);

$items = array ($parts[2] .$parts[3], );

}

fclose($file_handle);

?>

<?php foreach ($items as $i => $item): ?>

    <?php $mb->the_field('cb_ex3'); ?>

    <!-- similar to test #2, the same thing can be accomplished by simply
    adding array brackets "[]" to the name -->
    <input type="checkbox" name="<?php $mb->the_name(); ?>[]" value="<?php echo $item; ?>"<?php $mb->the_checkbox_state($item); ?>/> <?php echo $item; ?><br/>

<?php endforeach; ?>

所以在几百行代码中,我得到的只是最后一行。这是我正在使用的实际文件:http ://www.ouhsd.k12.ca.us/educational_services/curriculum/curriculum.csv

4

5 回答 5

4

在循环的每次迭代中,当您想要添加它时替换 $items,因此它只有最后一个值。

http://php.net/fgetcsv也可能对您有用。

于 2011-09-14T20:05:14.170 回答
2

您应该使用fgetcsv()( docs ) 函数,而不是尝试自己理解 CSV 数据。此外,您应该在循环文件时构建$items数组(而不是覆盖它),每次都添加一个新项目。

$file_handle = fopen('curriculum.csv', 'r');
fgets($file_handle); // this skips the csv header line
while (($parts = fgetcsv($file_handle)) !== FALSE) {
    $items[] = $parts[2] . ' ' . $parts[3];
}
fclose($file_handle);

foreach ($items as $item) {
    // Your HTML code goes here
    echo $item . PHP_EOL;
}

加分(你会看起来更酷,使用对象和迭代器!)

$file = new SplFileObject('curriculum.csv');
$file->setFlags(SplFileObject::READ_CSV);
foreach (new LimitIterator($file, 1) as $parts) {
    $items[] = $parts[2] . ' ' . $parts[3];
}

foreach ($items as $item) {
    // Your HTML code goes here
    echo $item . PHP_EOL;
}
于 2011-09-14T20:43:55.213 回答
0

您正在覆盖$items数组。我想建议一个更简单的方法

<code><pre><?php

    // in one step, load the datafile as an array, and loop over each line
    // then explode the line by comma, and add to $lines array
    foreach(file('curriculum.csv') as $line)
            $lines[] = explode(',',$line);

    // display the structure of the captured data
    print_r($lines);

?></pre></code>

我认为一旦您了解了此处捕获数据的结构,您就可以在输出循环中随意使用这些值。

code,prephp为方便添加标签

于 2011-09-14T20:24:44.920 回答
0

在您的情况下,项目应该是一个数组。在while循环之外初始化它

$items = array();

然后在while循环内

$items[] = array ($parts[2] .$parts[3], );

应该管用。

另请查看 fgetcsv 以及建议。

于 2011-09-14T20:09:55.947 回答
0

您的阵列需要一个额外的尺寸。

$i=0;
$items= new array(); // i think you need this for some fun reason
while (!feof($file_handle) ) {

    $line_of_text = fgets($file_handle);
    $parts = explode(',', $line_of_text);

    $items[$i] = array ($parts[2] .$parts[3], );

}
于 2011-09-14T20:11:29.097 回答