Using php, how can we read 5 rows from a csv file, call another function and then read next 5 rows and repeat this?

落爺英雄遲暮 提交于 2019-12-13 03:58:40

问题


Below is my Code. This code reads a csv file having around 100 student profiles. These profiles are displayed as a slideshow in this HTML page - http://www.depts.ttu.edu/honors/medallion-ceremony/test/. I would like to display a advertisement slide for every 5th profile. Please help !

$profiles = csv_to_array($_SERVER['DOCUMENT_ROOT'].'/...../profiles.csv');

function csv_to_array($filename, $delimiter=',', $enclosure='"', $escape = '\\')
{
    if(!file_exists($filename) || !is_readable($filename)) return false;
    $header = null;
    $data = array();
    $lines = file($filename);
    foreach($lines as $line) {
        $values = str_getcsv($line, $delimiter, $enclosure, $escape);
        if(!$header) 
            $header = $values;
        else 
            $data[] = array_combine($header, $values);
    }
return $data;
}

function displayProfiles($limit=100)
{
    global $profiles;
    $count = 1;
    foreach ($profiles as $profile)
    {
        if ($count <= $limit)
        {
            displayProfile($profile);
            $count++;
        }
    }   
}

function displayProfile($profile) {.....}

回答1:


You can check in your displayProfiles function where you are. Use the modulo operator http://php.net/manual/en/language.operators.arithmetic.php

Then you could do something like this in your loop:

if($count % 5 == 0) { 
   displayAdvertisement();
}


来源:https://stackoverflow.com/questions/49780573/using-php-how-can-we-read-5-rows-from-a-csv-file-call-another-function-and-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!