dqx36753 2011-09-14 20:02
浏览 53
已采纳

将CSV输出到数组

I am using WP Alchemy to create a meta box with multiple check boxes.

The trouble I'm having is, I have a csv list of academic courses that I want to create the check box options from. So I'm taking the csv turning it into an array that the boxes are made from. However with the code I have now, only the LAST line is created in the array.

I'm a self taught FrankinCoder when it comes to php, so bare with me...

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

So out of the few hundred lines of code, all I get is the last line. Here is the actually file I'm working with: http://www.ouhsd.k12.ca.us/educational_services/curriculum/curriculum.csv

Any help or suggestions are greatly appreciated!

  • 写回答

5条回答 默认 最新

  • duanguanya3052 2011-09-14 20:43
    关注

    You should be using the fgetcsv() (docs) function rather than trying to make sense of the CSV data yourself. Also, you should build the $items array (rather than overwriting it) as you loop over the file, adding a new item each time.

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

    Bonus points (you'll look cooler, using objects and iterators!)

    $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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办