Sort PHP Array Based on Number - php

I am trying to get a Downloads page working. I get a build number and details from a file, and I want to sort the array with that build number, currently 0.0.2 is above 1.0.3, and it will always keep the build number as it ascends. You can see the page at http://tattyseal.com/files/zaet
<?php
echo "<table border=0 style='text-align:left;border-spacing: 40px 0;'>";
echo "<tbody>";
echo "<img src='logoFile.png'/>";
echo "<h2>Promotions</h2>";
echo "<tr>";
echo "<th>Promotion</th>";
echo "<th>Version</th>";
echo "<th>Minecraft</th>";
echo "<th>Downloads</th>";
echo "</tr>";
echo "<tr>";
echo "<td>1.7.2-Recommend</td>";
echo "<td>0.0.2</td>";
echo "<td>1.7.2</td>";
echo "<td>(<a href='http://ts.tattyseal.com:8080/job/Zaet/2/artifact/build/libs/Zaet-dev-0.0.2.jar'>Universal</a>) (<a href='http://ts.tattyseal.com:8080/job/Zaet/2/artifact/build/libs/Zaet-dev-0.0.2.jar'>Deobf</a>) (<a href='http://ts.tattyseal.com:8080/job/Zaet/2/artifact/build/libs/Zaet-src-0.0.2.jar'>Src</a>)";
echo "</tr>";
echo "</tbody>";
echo "</table>";
echo "<table border=0 style='text-align:left;border-spacing: 40px 0;'>";
echo "<tbody>";
echo "<tr>";
echo "<h2>1.7.2 Downloads - Anything that is not Recommended can be unstable, there is a possibility of World Corruption</h2>";
echo "<th>Version</th>";
echo "<th>Minecraft</th>";
echo "<th>Time</th>";
echo "<th>Downloads</th>";
echo "</tr>";
$information = array();
$iterator = new RecursiveDirectoryIterator('versions');
foreach(new RecursiveIteratorIterator($iterator) as $filename => $file)
{
if (strpos($filename,'info') !== false)
{
array_push($information, file_get_contents($filename));
}
}
sort($information);
$information = array_reverse($information);
$info = $information;
$versions = array();
foreach($info as $i)
{
$array = explode(",", $i);
foreach($array as $line)
{
if(strpos($line, 'version') !== false)
{
if(strpos($line, 'mcversion') === false)
{
$array2 = explode(": ", $line);
array_push($versions, $array2[1]);
}
}
}
}
foreach($information as $info)
{
$array = explode(",", $info);
$mcversion = "";
$version = "";
$date = "";
$build = "";
foreach($array as $line)
{
if(strpos($line, 'mcversion') !== false)
{
$array3 = explode(": ", $line);
$mcversion = $array3[1];
}
if(strpos($line, 'version') !== false)
{
$array3 = explode(": ", $line);
$version = $array3[1];
}
if(strpos($line, 'date') !== false)
{
$array3 = explode(": ", $line);
$date = $array3[1];
}
if(strpos($line, 'build') !== false)
{
$array3 = explode(": ", $line);
$build = $array3[1];
}
}
echo "<tr><td>$version</td><td>$mcversion</td><td>$date</td><td>" . "(<a href='http://ts.tattyseal.com:8080/job/Zaet/$build/changes'>Changelog</a>) (<a href='http://ts.tattyseal.com:8080/job/Zaet/$build/artifact/build/libs/Zaet-dev-0.0.$build.jar'>Deobf</a>) (<a href='http://ts.tattyseal.com:8080/job/Zaet/$build/artifact/build/libs/Zaet-src-0.0.$build.jar'>Src</a>) (<a href='http://ts.tattyseal.com:8080/job/Zaet/$build/artifact/build/libs/Zaet-mod-0.0.$build.jar'>Universal</a>)</td></tr>";
}
echo "</tbody>";
echo "</table>";
?>
Thanks

Related

How to create dynamic table from both directory and CSV files

I need to create a table whose first column is populated from subdirectory names inside a directory and rest are from a CSV file. This have to be a dynamic table and table headers have to be added from the code. What's wrong with my code?
I am an absolute beginner. So, please ignore my stupidity.
$dir = 'D:\workspace';
$dirlist = preg_grep('/^([^.])/', scandir($dir));
$row = 1;
if (($handle = fopen("D:\workspace\demo\database.csv", "r")) !== FALSE) {
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
foreach ($dirlist as $rowdirectory)
{
echo '<td>' . $rowdirectory . '</td>';
echo '<td>'.$value.'</td>';
}
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
<?php
#------------------------------------------Function for Reading Directory-------------------------------------------
function readdirectory($dir)
{
$dirlist = preg_grep('/^([^.])/', scandir($dir)); // for all(./../anything that
starts with .)
//$dirlist = preg_grep('/[^.]/', scandir($dir)); //only . & ..
//$dirlist =preg_grep('/^[(^.)]/', scandir($dir));//only files that starts with .
return $dirlist;
}
#------------------------------------------Function for Reading CSV file-------------------------------------------
function readcsvfile($source)
{
$handle = fopen($source, "r");
$filecontent = null;
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
$filecontent[] = $data;
}
fclose($handle);
return $filecontent;
}
$filecontent= readcsvfile("D:\workspace\demo\database2.csv");
#-------------------Directory Function calling, header array cration and other declaration------------------------------------
$conf_prefix= "../";
$conf_suffix="index.php";
$headerarray= $filecontent[0];
#var_dump($headerarray);
$headersize= count($headerarray);
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
$dir = 'D:\workspace';
$dirlist= readdirectory($dir);
#------------------------------------------Creating 1st row/Header row of Table-------------------------------------------
echo '<tr>';
for($a=0; $a<$headersize;$a++)
{
echo '<td>'.$headerarray[$a].'</td>';
}
echo '</tr>';
#-----------------------------Creating Table elements by comparing both directory arrays and CSV file array-------------------------------------------
foreach ($dirlist as $rowdirectory)
{
foreach ($filecontent as $value) {
$num = count($value);
if ($rowdirectory== $value[0])
{
$link= $conf_prefix. $rowdirectory."/".$conf_suffix;
echo '<tr>';
echo '<td> ' . $rowdirectory . ' </td>';
for( $c=1; $c < $num; $c++) {// loop for csv file
{
echo '<td>'.$value[$c].'</td>';//else print "value"
}
}
echo '</tr>';
}
}
}
?>

Moving empty values of an array to the last position

I'm pulling an array from an external API, And I've got some help with usort on here, And It pushes it to the bottom, and empty values are on top. I tried using unset but that just emptied out my entire realArrival values.
e.g.
$fromThis = array(
"realArrival": "",
"realArrival": "Confirm. 06:18",
"realArrival": "Confirm. 06:19"
);
Into:
$intoThis = array(
"realArrival": "Confirm. 06:18",
"realArrival": "Confirm. 06:19",
"realArrival": ""
);
Here is my code on how I tried to do it. I'm sure you are shaking your head at this but here it goes.
$url = 'http://apis.is/flight?language=en&type=arrivals';
$json = file_get_contents($url);
$results = json_decode($json, TRUE);
$results = $results['results'];
function cmp($a, $b) {
return strcmp($a['realArrival'], $b['realArrival']);
}
//Sort Time
usort($results, "compare_time");
function compare_time($a,$b) {
$splitA= count(explode(' ',$a['realArrival']));
$splitB= count(explode(' ',$a['realArrival']));
if($splitA==2 && $splitB==2)
{
$first_time = strtotime(explode(' ',$a['realArrival'])[1]);
$second_time = strtotime(explode(' ',$b['realArrival'])[1]);
if($first_time==$second_time)
{
return strcmp($b['realArrival'], $a['realArrival']);
}
return ($second_time < $first_time) ? 1: 0;
}
return strcmp($a['realArrival'], $b['realArrival']);
}
echo '<table class="highlight bordered responsive-table grey darken-2 col s6">';
echo "<tr>";
echo '<th>Date</th>';
echo '<th>Flight Number</th>';
echo '<th>Airline</th>';
echo '<th>From</th>';
echo '<th>Schedule. Time</th>';
echo '<th>Status</th>';
echo "</tr>";
foreach ($results as $item => $val) {
echo "<tr>";
echo '<td>'.$val['date'].'</td>';
echo '<td>'.$val['flightNumber'].'</td>';
echo '<td>'.$val['airline'].'</td>';
echo '<td>'.$val['from'].'</td>';
echo '<td>'.$val['plannedArrival'].'</td>';
// HERE I TRIED TO TARGET THE EMPTY VALUES
if ($val === "") {
unset($results[$item]);
$results[] = $val;
echo '<td style="font-weight: bold;">'.$val['realArrival'].'</td>';
}
echo '</tr>';
}
I know this might seem clunky, but you could always just do something like...
$items_with_real_arrivals = array();
$items_without_real_arrivals = array();
foreach ($results as $item => $val) {
if ($item[‘realArrival’] === "") { $items_without_real_arrivals.push($item); }
else $items_with_real_arrivals.push($item);
}
$reordered_items = array();
for ($i=0; $i<count($items_with_real_arrivals); $i++) {
$reordered_items.push($item);
}
for ($i=0; $i<count($items_without_real_arrivals); $i++) {
$reordered_items.push($item);
}
foreach ($reordered_items as $item => $val) {
echo "<tr>";
echo ' <td>'.$val['date'].'</td>';
echo ' <td>'.$val['flightNumber'].'</td>';
echo ' <td>'.$val['airline'].'</td>';
echo ' <td>'.$val['from'].'</td>';
echo ' <td>'.$val['plannedArrival'].'</td>';
echo ' <td style="font-weight:bold;">' . $val['realArrival'].'</td>';
echo '</tr>';
}

Break PHP while loop if variable is empty

I have a CSV (attached below) that I am looping through with PHP. Note: the Peter entry is missing an Extension number.
How do I break the loop if any $cell (like Extension) is empty
<?php
echo "<html><body><table>\n\n";
$f = fopen("users.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
~
Forename,Surname,Extension
Jim,Carey,1973
Peter,Robertson,
Try using this -
<?php
echo "<html><body><table>\n\n";
$f = fopen("users.csv", "r");
while (($line = fgetcsv($f)) !== false) {
$row = "<tr>";
$is_empty = false;
foreach ($line as $cell) {
if ($cell !== '') {
$row .= "<td>" . htmlspecialchars($cell) . "</td>";
} else {
$is_empty = true;
}
}
$row .= "</tr>\n";
if ($is_empty) {
continue;
} else {
echo $row;
}
}
fclose($f);
echo "\n</table></body></html>";
?>
This solution will print the row only if all the fields have value. You can use break instead of continue, if you want to break the loop.

Reverse Sort by particular column for each loop in php

This is csv file :
40405,Vodafone,2
405806,Aircel,1
41303,Etisalat,1
45201,MobilFone,3
51010,Telkomsel,1
63903,Zain,1
63905,yu,2
64005,Airtel,1
I tried using the rsort, ksort, asort, but unable to sort according to the column.
Echoing using the for each loop in php : I am trying to sort the whole data according to the 3rd column in reverse order( descending) ,
$f = fopen("file.csv", "r");
while (($line = fgetcsv($f)) !== false)
{
echo "<tr id='trdata'>";
foreach ($line as $cell)
{
echo "<td>" . htmlspecialchars($cell). "</td>";
}
echo "</tr>\n";
}
Thanks.
$f = fopen("file.csv", "r");
$fileData = array();
while (($line = fgetcsv($f)) !== false) {
$fileData[] = $line;
}
echo arrayAsTable($fileData) . "<br />";
usort($fileData, function($a, $b) {
return $b[2] - $a[2];
});
echo arrayAsTable($fileData);
function arrayAsTable($array)
{
$out = "<table>";
foreach ($array as $line) {
$out .= "<tr id='trdata'>";
foreach ($line as $cell) {
$out .= "<td>" . htmlspecialchars($cell) . "</td>";
}
$out .= "</tr>";
}
$out .= "</table>";
return $out;
}

PHP Search CSV file. Search filter minimum characters

I'm noob at PHP. I have PHP script to search CSV file.
How can I add search filter minimum x characters else it shows error message?
<?php
if ( !empty ( $_GET['search'] ) ) {
$search = mb_strtolower($_GET['search']);
$lines = file('file.csv');
$found = false;
foreach($lines as $line)
{
$line = mb_strtolower($line);
if(strpos($line, $search) !== false)
{
$line = explode(',', $line);
$found = true;
$str = $line[0];
$str = strtoupper($str);
echo "<div class='datagrid'><table><thead><tr><th>MODEL</th><th width='50px;'>QUANTITY</th><th width='155px;'>MAIL</th></tr></thead><tbody><tr>";
echo "<td style='font-weight:bold;'>" . $str; echo "</td>";
echo "<td>" . $line[1]; echo "</td>";
echo "<td><a href='mailto:mailaddress?subject=$str' id='button'>Send</a></td>";
echo "</tr>";
echo "</tbody></table></div>";
}
}
if(!$found) {
echo 'Nothing found.';
}
}
?>
You can use the strlen function to know how many characters search term has
http://php.net/manual/en/function.strlen.php
<?php
$search_min_len = 3;//Change this to your needs
if ( !empty ( $_GET['search'] ) ) {
$search = mb_strtolower($_GET['search']);
if(strlen($search ) >= $search_min_len)
{
$lines = file('file.csv');
$found = false;
foreach($lines as $line)
{
$line = mb_strtolower($line);
if(strpos($line, $search) !== false)
{
$line = explode(',', $line);
$found = true;
$str = $line[0];
$str = strtoupper($str);
echo "<div class='datagrid'><table><thead><tr><th>MODEL</th><th width='50px;'>QUANTITY</th><th width='155px;'>MAIL</th></tr></thead><tbody><tr>";
echo "<td style='font-weight:bold;'>" . $str; echo "</td>";
echo "<td>" . $line[1]; echo "</td>";
echo "<td><a href='mailto:mailaddress?subject=$str' id='button'>Send</a></td>";
echo "</tr>";
echo "</tbody></table></div>";
}
}
if(!$found) {
echo 'Nothing found.';
}
}
else
{
echo 'Minimum '.$search_min_len.' characters error';
}
}
?>
Hope it helps

Categories