当前位置: 首页>>代码示例>>PHP>>正文


PHP csv_to_array函数代码示例

本文整理汇总了PHP中csv_to_array函数的典型用法代码示例。如果您正苦于以下问题:PHP csv_to_array函数的具体用法?PHP csv_to_array怎么用?PHP csv_to_array使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了csv_to_array函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: process_spreadsheet

function process_spreadsheet($path)
{
    $keys = array();
    $newArray = array();
    $data = csv_to_array($path, ',');
    // Set number of elements (minus 1 because we shift off the first row)
    $count = count($data) - 1;
    //Use first row for names
    $labels = array_shift($data);
    foreach ($labels as $label) {
        $keys[] = $label;
    }
    // Add Ids, just in case we want them later
    $keys[] = 'id';
    for ($i = 0; $i < $count; $i++) {
        $data[$i][] = $i;
    }
    // Bring it all together
    for ($j = 0; $j < $count; $j++) {
        $d = array_combine($keys, $data[$j]);
        if (!is_empty_str($d["ID"])) {
            //            $newArray[$j] = $d;
            $newArray[$d["ID"]] = $d;
        }
    }
    return $newArray;
}
开发者ID:aw3s0me,项目名称:RDF_Parser,代码行数:27,代码来源:convert.php

示例2: run

 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     function csv_to_array($filename = '', $delimiter = ',')
     {
         if (!file_exists($filename) || !is_readable($filename)) {
             return FALSE;
         }
         $header = NULL;
         $data = array();
         if (($handle = fopen($filename, 'r')) !== FALSE) {
             while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
                 if (!$header) {
                     $header = $row;
                 } else {
                     $data[] = array_combine($header, $row);
                 }
             }
             fclose($handle);
         }
         return $data;
     }
     $csvFile = public_path() . '/csvs/categories.csv';
     $datas = csv_to_array($csvFile);
     DB::table('categories')->delete();
     foreach ($datas as $data) {
         Categories::create($data);
     }
 }
开发者ID:boluge,项目名称:Glucide,代码行数:33,代码来源:CategoryTableSeeder.php

示例3: run

 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     function csv_to_array($filename = '', $delimiter = ',')
     {
         if (!file_exists($filename) || !is_readable($filename)) {
             return FALSE;
         }
         $header = NULL;
         $data = array();
         if (($handle = fopen($filename, 'r')) !== FALSE) {
             while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
                 if (!$header) {
                     $header = $row;
                 } else {
                     $data[] = array_combine($header, $row);
                 }
             }
             fclose($handle);
         }
         return $data;
     }
     $csvFile = public_path() . '/exams.csv';
     $areas = csv_to_array($csvFile);
     DB::table('exams')->insert($areas);
 }
开发者ID:kousiksatish,项目名称:experience,代码行数:30,代码来源:ExamsTableSeeder.php

示例4: print_hotels

function print_hotels()
{
    $hotels = csv_to_array('hotels.csv');
    foreach ($hotels as $hotel) {
        #var_dump($hotel);
        $shorttel = str_replace(' ', '', $hotel["tel"]);
        $img = isset($hotel["img"]) && $hotel["img"] ? $hotel["img"] : 'generic_hotel.jpg';
        echo <<<EOL
<div class='hotel'>
  <a class='imga' href="img/hotels/{$img}">
  <img src="img/hotels/_{$img}" />
  </a>
  <h3>{$hotel["name"]}</h3>

  <div class="address">
  {$hotel["street"]}<br>
  {$hotel["loc"]}
  </div>

  <a class="web" href="{$hotel["url"]}">{$hotel["url"]}</a>
  <a class="mail" href="mailto:{$hotel["email"]}">contact</a>
  <a class="tel" href="tel:{$shorttel}">{$hotel["tel"]}</a>
</div>
EOL;
    }
}
开发者ID:cythoning,项目名称:lisa_symposium_2016_homepage,代码行数:26,代码来源:funcs.php

示例5: csv_to_array

 protected function csv_to_array($data)
 {
     if (defined('STRICT_TYPES') && CAMEL_CASE == '1') {
         return (array) self::parameters(['data' => DT::TEXT])->call(__FUNCTION__)->with($data)->returning(DT::TYPE_ARRAY);
     } else {
         return csv_to_array($data);
     }
 }
开发者ID:tfont,项目名称:skyfire,代码行数:8,代码来源:csv.class.php

示例6: pre_import

function pre_import($filename)
{
    $results = array();
    foreach (csv_to_array($filename, FALSE) as $csv) {
        #var_dump($csv);
        $results[] = array('firstname' => $csv[1], 'lastname' => $csv[2], 'phone' => $csv[3], 'email' => $csv[4]);
    }
    return $results;
}
开发者ID:efoft,项目名称:studi,代码行数:9,代码来源:func.php

示例7: createBits

 public function createBits($csv)
 {
     #load csv to an array
     $local = csv_to_array($csv);
     foreach ($local as $singleBit) {
         $container = array_values($singleBit);
         $T = new BitWord();
         $T->setWord(trim($container[0]));
         $T->setDefinition(trim($container[1]));
         $T->setSynonym(trim($container[2]));
         #ADD INITIALIZED BIT TO bit property array
         $this->bits[] = $T;
         unset($T);
     }
 }
开发者ID:Lockf0rc,项目名称:RunBitWord,代码行数:15,代码来源:BitFactory.php

示例8: uploadFiletoDB

function uploadFiletoDB($UserFileName)
{
    $TransactionArray = array();
    $TblName = TableName;
    $FileName = $_FILES[$UserFileName]['name'];
    $FileServerName = $_FILES[$UserFileName]['tmp_name'];
    $CSVFIle = 'transactionTable.csv';
    $CSVDelimiter = ';';
    $ValidRecordswrited = 0;
    $InvalidRecords = 0;
    if (getFileExtension($FileName) == 'xlsx') {
        convertXLStoCSV($FileServerName, $CSVFIle);
        $CSVDelimiter = ',';
    } else {
        $CSVFIle = $FileServerName;
    }
    $TransactionArray = csv_to_array($CSVFIle, $CSVDelimiter);
    if (sizeof($TransactionArray) > 100000) {
        echo '<br>';
        echo "Error - file rows cont is to much";
        return false;
    }
    $Connection = mysql_connect(ServerName, UserName, Password);
    $db_selected = mysql_select_db(DBName, $Connection);
    if (!$Connection) {
        die("Connection failed: " . mysql_error());
    }
    foreach ($TransactionArray as $Line) {
        if (checkTransactionRecord($Line)) {
            $Request = "INSERT INTO {$TblName}(`Account`, `Description`, `CurrencyCode`, `Ammount`) VALUES ('{$Line['Account']}','{$Line['Description']}','{$Line['CurrencyCode']}',{$Line['Amount']})";
            $result = mysql_query($Request);
            if (!$result) {
                echo 'Query error: ' . mysql_error();
            } else {
                $ValidRecordswrited++;
            }
        } else {
            $InvalidRecords++;
        }
    }
    mysql_close($Connection);
    echo '<br> <br>';
    echo "Valid records writed to DataBase: {$ValidRecordswrited}";
    echo '<br>';
    echo "Invalid records count: {$InvalidRecords}";
}
开发者ID:pj-infest,项目名称:ElifTechTask,代码行数:46,代码来源:upload.php

示例9: array

<?php

$sDestinationFile = __DIR__ . '/../languages.php';
$aSourcesFiles = array('languages' => __DIR__ . '/Languages.csv', 'directionalities' => __DIR__ . '/LanguagesDirectionality.csv', 'scripts' => __DIR__ . '/LanguagesScripts.csv');
$aData = csv_to_array($aSourcesFiles['languages']);
$aDirectionalitiesSrc = csv_to_array($aSourcesFiles['directionalities']);
foreach ($aDirectionalitiesSrc as $sLanguageCode => $aDirectionality) {
    if (isset($aData[$sLanguageCode])) {
        $aData[$sLanguageCode]['Directionality'] = $aDirectionality['Directionality'];
    }
}
$aScriptsSrc = csv_to_array($aSourcesFiles['scripts']);
foreach ($aScriptsSrc as $sLanguageCode => $aScript) {
    if (isset($aData[$sLanguageCode])) {
        $aData[$sLanguageCode]['Script'] = $aScript['Script'];
    }
}
file_put_contents($sDestinationFile, "<?php\n\nreturn " . var_export($aData, true) . ";\n");
/**
 * Convert a comma separated file into an associated array.
 * The first row should contain the array keys.
 *
 * Example:
 *
 * @param string $sFilename Path to the CSV file
 * @param string $sDelimiter The separator used in the file
 * @return array
 * @link http://gist.github.com/385876
 * @author Jay Williams <http://myd3.com/>
 * @copyright Copyright (c) 2010, Jay Williams
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
开发者ID:forxer,项目名称:languages-list,代码行数:31,代码来源:Build.php

示例10: csv_to_array

function csv_to_array($filename = '/Users/emmanuel.manyike/Desktop/use.csv', $delimiter = ';')
{
    if (!file_exists($filename) || !is_readable($filename)) {
        echo "file does not exist\n";
    }
    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE) {
        echo "file exist\n";
        $handle2 = fopen('/private/var/www/spree.local/htdocs/app/code/local/Touchlab/SpreeDbUpdates/data/spreedbupdates_setup/data-upgrade-0.1.52-0.1.53.php', 'w');
        $counter = 0;
        while ($row = fgets($handle)) {
            $row = trim($row, "\r\n");
            $sizedata = explode(';', $row);
            $string = "UPDATE eav_attribute_option SET sort_order = {$sizedata['1']} WHERE option_id = {$sizedata['0']}; " . PHP_EOL;
            if ($handle2) {
                fwrite($handle2, $string);
            } else {
                echo "inside else";
                echo $string;
            }
        }
        echo "done bro";
        fclose($handle2);
        fclose($handle);
    }
    return $data;
}
//UPDATE eav_attribute_option SET sort_order = 0 WHERE option_id = 832;
$csvData = csv_to_array();
开发者ID:manyike,项目名称:api,代码行数:30,代码来源:testingSizes.php

示例11: stripslashes

<?php

require_once "functions.php";
// Get array from CSV
$str = stripslashes($_POST["csv"]);
$data = csv_to_array($str);
// Find row with the most columns
$col_count = 0;
foreach ($data as $row) {
    $col_count = count($row) > $col_count ? count($row) : $col_count;
}
?>
<div class="fog"></div>

<div class="edit_table" style="display:none;">

	<div class="modal_window_header" class="clearfix"> 
		Edit Table
		<a class="close_modal" href=""></a> 
	</div>
	
	<div class="edit_table_content">
		<table>
			
			<tr>
				<td class="row_selector blank"></td>
				<?php 
for ($col = 0; $col < $col_count; $col++) {
    ?>
<td class="column_selector"><?php 
    echo num_to_chars($col + 1);
开发者ID:Shairi,项目名称:directus-5-legacy,代码行数:31,代码来源:edit_table.php

示例12: csv_to_array

<?php 
$news = csv_to_array('data/science_advisory_committee.csv');
// sort by date, newest on top
function compare_lastname($a, $b)
{
    return strnatcmp($a['last_name'], $b['last_name']);
}
usort($news, 'compare_lastname');
echo "<ul>\n";
foreach ($news as $v) {
    echo "  <li>{$v['first_name']} {$v['last_name']}</li>\n";
}
echo "</ul>\n";
开发者ID:AstroPhysicsUZH,项目名称:lisa_symposium_2016_homepage,代码行数:13,代码来源:science_advisory_committee.php

示例13: csv_to_array

 <?php 
require_once "./includes/db_connection.php";
require_once "./includes/cvsProcess.php";
?>

<?php 
$the_array[] = csv_to_array('transactions.csv');
foreach ($the_array as $array_row) {
    foreach ($array_row as $array_element) {
        //echo print_r($array_element);
        //    echo $array_element['Date'];
        //    echo "<br>";
        $trans_date = $array_element['Date'];
        $original_description = addslashes($array_element['Original Description']);
        $amount = $array_element['Amount'];
        $transaction_type = $array_element['Transaction Type'];
        $trans_date = date("Y-m-d", strtotime($trans_date));
        $query = "INSERT INTO mintImport (trans_date, original_description, amount, transaction_type)\n    VALUES ('{$trans_date}', '{$original_description}', '{$amount}', '{$transaction_type}')";
        $result = mysqli_query($connection, $query);
        if (!$result) {
            die("Database query failed.");
        }
    }
}
#print_r($_GET)
#echo $deviceName;
# ?deviceName=devicenamed&sensorName=sensorNamed&sensorReading=32
开发者ID:jasonkirk,项目名称:financialProcess,代码行数:27,代码来源:import_to_db.php

示例14: find_all_files

// on récupère la liste des images contenues dans le répertoire des tiles
$tiles = find_all_files($TILES_DIR);
$tilesImg = array();
foreach ($tiles as $index => $filename) {
    if ($filename == $IMG_SPACE) {
        unset($tiles[$index]);
    } else {
        $tilesImg[] = imagecreatefromstring(file_get_contents($TILES_DIR . $filename));
    }
}
// on charge l'image contenant les espaces
$spaceImg = imagecreatefromstring(file_get_contents($TILES_DIR . $IMG_SPACE));
// on récupère le contenu du fichier CSV
$fileContent = file_get_contents($FILE_FACES);
// on extrait le contenu CSV dans un tableau
$tabFaces = csv_to_array($fileContent, $CSV_DELIMITER);
// génération des images
// on va calculer les dimensions des images pour chaque face
$scale = $TILE_HEIGHT / $TILE_HEIGHT_M;
foreach ($tabFaces as $index => $faceInfos) {
    // HEIGHT
    $faceInfos['img_height'] = $TILE_HEIGHT;
    // WIDTH : conversion en fonction des mètres
    $faceInfos['img_width'] = round($faceInfos['length'] * $scale);
    // FILE NAME
    $faceInfos['filename'] = $faceInfos['code'] . "_" . $faceInfos['face'] . ".png";
    // on calcule le nombre de tiles qu'il faut mettre dans l'image
    $nbTiles = floor($faceInfos['img_width'] / $TILE_WIDTH);
    // on calcule le nombre d'espaces
    if ($nbTiles > 0) {
        $nbSpaces = $nbTiles - 1;
开发者ID:BGCX261,项目名称:zombie-feria-svn-to-git,代码行数:31,代码来源:texture_generate.php

示例15: foreach

        foreach ($gcdata as $k) {
            $p[] = $count == 0 ? '"' . $k . '"' : $k;
            $count++;
        }
        $chart_data[] = "[" . implode(",", $p) . "]";
    }
    foreach ($gheader as $d) {
        $header_data[] = '"' . $d . '"';
    }
    $header_data = "[" . implode(",", $header_data) . "]";
    $chart_data = implode(",", $chart_data);
    $full_chart_data = "[" . $header_data . "," . $chart_data . "]";
    return $full_chart_data;
}
$DataFile = $_SERVER['DOCUMENT_ROOT'] . "/googlechart/tread.csv";
$GChartData = csv_to_array($DataFile);
$full_chart_data = BuildDataTable($GChartData['data'], $GChartData['header']);
?>

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable(<?php 
echo $full_chart_data;
?>
);

    var options = {
        title: '',
开发者ID:krupalpatel92,项目名称:CSV-to-Gchart,代码行数:31,代码来源:tread.php


注:本文中的csv_to_array函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。