Problem with loop printing csv contents in php - php

This snippet just about works :|
I can spit out all of the array data, but what I want is to be able to print out the data column by column.
function processCSV()
{
global $uploadFile;
$loadLocationCsvUrl = fopen($uploadFile,"r");
if ($loadLocationCsvUrl <> false)
{
while ($locationFile = fgetcsv($loadLocationCsvUrl, ','))
{
$csvCols = array(
'country' => $locationFile[9],
'open' => $locationFile[4],
'officeid' => $locationFile[2]
);
foreach($csvCols as $locationData)
{
if ($locationData == '') {
echo "<p>" . "blank" . "</p>";
}
else
{
echo "<p>" . $locationData . "</p>";
}
}
}
}
fclose($loadLocationCsvUrl);
}
processCSV();
I thought this would work:
echo "<p>" . $locationData['country'] . "</p>";
But if I do that I see a incorrectly formatted page, like the below (uploaded screenshot).
http://www.imageupload.org/?d=9C676F041
I managed to work this out with a different implementation, I switched to a 2d array, the table rendering was never the issue it was obtaining the data.
<?php
function processCSV()
{
global $uploadFile;
$loadLocationCsvUrl = fopen($uploadFile,"r");
if ($loadLocationCsvUrl <> false)
{
while ($locationFile = fgetcsv($loadLocationCsvUrl, ','))
{
$officeId = $locationFile[2];
$country = $locationFile[9];
$open = $locationFile[4];
echo "<table>";
echo "<tr>";
echo "<td>$officeId</td>";
echo "<td>$country</td>";
echo "<td>$open</td>";
echo "</tr>";
echo "</table>";
}
}
fclose($loadLocationCsvUrl);
}
processCSV();
?>
Thank you for responding and sorry if I wasted anybodies time.

It sounds like you want to display the output colum-wise. In that case a <table> is the intended markup. But I would first simplify your code:
// read in
$csv = array_map("str_getcsv", file($uploadFile));
// output
print "<table>";
foreach ($csv as $row) {
print <<<HTML
<tr>
<td>$row[9]</td>
<td>$row[4]</td>
<td>$row[2]</td>
</tr>
HTML;
}
If you don't use the associative array keys for the columns, then there's no point in creating them.

<p> is a block element, so each successive one goes to a new line by design. You can set 'display: inline;' in your css if you want, but then why use <p>?
You could use an inline element like <span> or use 'float: left' to make a block element behave as you want.
That's assuming the data isn't appropriate for tabulation.

make a parent table then tr and td,
now, inside this td, make a table and print a column of td-trs
then close this table
print a new td in parent
repeat a table of one column trs
example....
<table><tr><td>
<table>
<tr><td>col1stuff1</td></tr>
<tr><td>col1stuff2</td><tr>
<tr><td>col1stuff3</td><tr>
</table>
</td><td>
<table>
<tr><td>col2stuff1</td></tr>
<tr><td>col2stuff2</td><tr>
<tr><td>col2stuff3</td><tr>
</table>
</td><td>
<table>
<tr><td>col3stuff1</td></tr>
<tr><td>col3stuff2</td><tr>
<tr><td>col3stuff3</td><tr>
</table>
</td></tr></table>

Related

Create a bidimensional array in php

I confess that I am a beginner. My goal is to be able to summarize in a two-dimensional table the amount per month (in column) for each class (in line). After doing a lot of research, I arrived at this stage in my project.
My problem is , I get the result with months repeating in columns like here.
Here is my code.
This is my sql code : "SELECT classe, mois, sum_ec FROM journal"
This is my php code :
<?php
$tableau = array();
$tblClasse = array();
$rt = mysqli_query($db, $req_sit);//execute la requete
while ($row = $rt->fetch_assoc()){ //forme le tableau
$tableau[$row['classe']][$row['mois']] = $row['sum_ec'];
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
}
echo '<table border="1">
<tr>
<th> </th>';
foreach ($tblClasse as $classe) {
echo '<th>' . htmlspecialchars($classe) . '</th>';
}
echo '</tr>';
foreach ($tableau as $mois=>$value) {
echo '<tr>';
$new_line = TRUE;
foreach ($tblClasse as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
$display = isset($value[$classe]) ? $value[$classe] : " ";
echo '<td>' . $display . '</td>';
}
echo '</tr>';
}
?>
Can someone tell me what mistake I made?
The problem is in this part of your code:
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
You are adding months (Fev, Mar) to the array and trying to check if it contains classes (PS, MS etc.) which is impossible, and this condition always returns true, so Feb is added to the $tblClasse array at each iteration. You must either check months or classes and add months or classes to the array respectively. And if you want the array to contain unique values (for example, months), use keys instead of values:
if (!array_key_exists ($row['mois'],$tblClasse)) {
$tblClasse[$row['mois']] = 1;
}
Where 1 can be replaced with any other value.
In the further part of your code use the keys, not values of $tblClasse array to form the table heading.
foreach (array_keys ($tblClasse) as $mois) {
echo '<th>' . htmlspecialchars($mois) . '</th>';
}
Eureka! It worked. I just had to change the line for the values ​​to "array_keys"
foreach (array_keys($tblClasse) as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
as well and boom! It's perfect. Thank you very much my dear. You have given me a lot of happiness.

Table Column to hyperlink

I currently have php generating a table from csv. I use tags to identify columns, which i later use jquery and datatables to sort, filter, and highlight.
I am looking for a way to make the data from a column into links. the data is case numbers and there is a predefinited link, you would just added the case number to the end of it and that would be your link to another page.
Do anyone know how I can achieve this, I'll include a snippet below so you can get an idea of how the table is created.
<th>ASUP Created Flag</th>
</tr>
</thead>
<tbody>
END;
//here we open the csv file as read-only
$f = fopen("cases.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
//this starts the alternation of tr and td for building the table
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
//after the table has been built, this is where we close it out
echo "\n</tbody></table></section></div></body></html>";
?>
Are you asking for something like:
<th>ASUP Created Flag</th>
or for the actual cell data:
foreach ($line as $cell) {
echo "<td><a href='some url'>" . htmlspecialchars($cell) . "</a></td>";
}
If you're wondering what some url should be, well that's completely up to you. If it depends on the cell data, then you would need some way to reference a URL given the cell data (either through a lookup array, database table, just some way to associate a URL with the value in $cell).
Update
If you want your case numbers to be links, and the value of the cell is the exact value you want to use in the URL, you can do something like this:
$count = 0;
foreach ($line as $cell) {
$cell = htmlspecialchars($cell);
if($count == 0) {
echo "<td><a href='/case/" . $cell . "'>" . $cell . "</a></td>";
} else {
echo "<td>" . $cell . "</td>";
}
$count++;
}

PHP explode multidimensional array

I am using file_get_contents() to import a text file.
In the text file, the format goes as below (example):
3434,83,8732722
834,93,4983293
9438,43933,34983
and so forth... basically it follows the pattern: integer, comma to split it, second integer, another comma to split it, third integer, then a new line begins. I need to get this into a table with the format following accordingly. So in other words, I would have a 3 column table and each new line in the text file would be a new row in the table.
This must be transcoded into a simple html table with <table> <tr> and <td>
I have never worked with multidimensional arrays and splitting text with that. This is why I'm seeking assistance. I really appreciate it! :)
You can do following :
$filename = 'abc.txt';
$content = file_get_contents($filename);
$explodedByBr = explode('<br/>', $content);
$table = "<table border='1'>";
foreach ($explodedByBr as $brExplode) {
$explodedByComma = explode(',', $brExplode);
$table .= "<tr>";
foreach ($explodedByComma as $commaExploded) {
$table .= "<td>" .$commaExploded. "</td>";
}
$table .= "<tr/>";
}
$table .= "</table>";
echo $table;
abc.txt has data in following format :
3434,83,8732722
834,93,4983293
9438,43933,34983
<?php
$file = 'path/to/file.txt';
echo '<table>';
while(!feof($file)) {
$line = fgets($file);
echo '<tr><td>' . implode('</td><td>',explode(',',$line)) . '</td></tr>';
}
echo '</table>';
?>
Try this:
Read the file into an array and then column'ize it by processing each line of the array by passing it through array_walk.
<?php
function addElements( &$v, $k ) {
$v1 = explode( ',', $v ); // break it into array
$v2 = '';
foreach( $v1 as $element ) {
$v2 .= '<td>'.$element.'</td>';
// convert each comma separated value into a column
}
$v = '<tr>'.$v2.'</tr>'; // add these columns to a row and return
}
// read the whole file into an array using php's file method.
$file = file( '1.txt' );
// now parse each line of the array so that we convert each line into 3 columns.
// For this, i use array_walk function which calls a function, addElements,
// in this case to process each element in the array.
array_walk( $file, 'addElements' );
?>
<html>
<head></head>
<body>
<table border="0">
<?php echo implode('',$file);?>
</table>
</body>
</html>
Hope it helps. See the php doc for file and array_walk. These are simple and convenient functions.

Echo selective data (rows) from multidimensional array in PHP

I have an array coming from a .csv file. These are coming from a real estate program. In the second column I have the words For Sale and in the third column the words For Rent that are indicated only on the rows that are concerned. Otherwise the cell is empty. I want to display a list rows only For Sale for example. Of course then if the user clicks on a link in one of the rows, the appropriate page will be displayed.
I can't seem to target the text in the column, and I can't permit that the words For Sale be used throughout the entire array because they could appear in another column (description for example).
I have tried this, but to no avail.
/* The array is $arrCSV */
foreach($arrCSV as $book) {
if($book[1] === For Sale) {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
I also tried this:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
Do you mean:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div></div>';
}else{
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
}
I found a solution here:
PHP: Taking Array (CSV) And Intelligently Returning Information
$searchCity = 'For Sale'; //or whatever you are looking for
$file = file_get_contents('annonces.csv');
$results = array();
$lines = explode("\n",$file);
//use any line delim as the 1st param,
//im deciding on \n but idk how your file is encoded
foreach($lines as $line){
//split the line
$col = explode(";",$line);
//and you know city is the 3rd element
if(trim($col[1]) == $searchCity){
$results[] = $col;
}
}
And then:
foreach($results as $Rockband)
{
echo "<tr>";
foreach($Rockband as $item)
{
echo "<td>$item</td>";
}
echo "</tr>";
}
As you can see I'm learning. It turns out that by formulating a question, a series of similar posts are displayed, which is much quicker and easier than using google. Thanks.

Library to print tabular data on a web page

Are there any libraries I can use to pretty print tabular data(from php code)?
What I mean is, if I have:
$headers = array("name", "surname", "email");
$data[0] = array("bill", "gates", "bill#microsoft.com");
$data[1] = array("steve", "jobs", "steve#apple.com");
/*...*/
pretty_print($headers, $data);
It will print my data neatly(preferably using tableless html code & css)?
Why not just write your own?
I wrote an example below. Note that I haven't tested this - it's the definition of "air code" so beware. Also, you could add checks to make sure count($rows) > 0 or to make sure count($rows) == count($headers) or whatever..
The point is just that it isn't that hard to throw something together:
function displayTable($headings, $rows) {
if !(is_array($headings) && is_array($data)) {
return false; //or throw new exception.. whatever
}
echo "<table>\n";
echo "<thead>\n";
echo "<tr>\n";
foreach($headings as $heading) {
echo "<th>" . $heading . "</th>\n";
}
echo "</tr>\n";
echo "</thead>\n";
echo "<tbody>"
foreach($data as $row) {
echo "<tr>\n";
foreach($row as $data) {
echo "<td>" . $data . "<td>";
}
echo "</tr>\n";
}
echo "</tbody>\n";
echo "</table>\n";
}
As a final note, why would you want to use HTML/CSS layouts rather than tables for this? Tables are for tabular data which this obviously is. This is their purpose!
The trend against using tables is for using them to layout pages. They're still quite valid for tabular data, and will be for the foreseeable future.

Categories