Solved

dynamic referencing the number of columns in the csv to the number of sliders

Posted on 2013-10-25
11
791 Views
Last Modified: 2013-10-28
I have a web page which has a paginated format for the display of a CSV file. I have range sliders to control the display of the CSV row values. The total range sliders are based on the total columns of the CSV file (The CSV file comes from another source and the total columns is unknown before hand).

I have the following code which works fine assuming the total columns in my CSV file is 5. However, I need the below code for dynamic number of columns.

This is the code I have so far. I am really thankful to another expert of this group (GaryC123) who helped me out in designing this code.

<!DOCTYPE html>
<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="js/simple-slider.js"></script>
<style type="text/css">
	body {
		font-family: Verdana;
		font-size: 13px;
	}
	
	a {
		text-decoration: none;
	}
	
	a:hover {
		text-decoration: underline;
	}
</style>
<link href="css/simple-slider.css" rel="stylesheet" type="text/css" />
<link href="css/simple-slider-volume.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php 
require_once "Paginated.php";
require_once "DoubleBarLayout.php";

$names = file('demo.csv');
isset($_GET['page'])?$page = $_GET['page']:$page=1;

$pagedResults = new Paginated($names, 20, $page);
$handle = fopen('demo.csv', 'r');
  if (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
    {
    }
	 
echo "<table id='kwTable' border='4' bgcolor='#adb214' style='float:center; margin:100'>";
echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
?>
<tbody id="kwBody">
<?php
//when $row is false loop terminates
$header = true;
if (!$page) $page = 1;
isset($_GET['slider1'])?$s1=$_GET['slider1']:$s1=0;
isset($_GET['slider2'])?$s2=$_GET['slider2']:$s1=0;
isset($_GET['slider3'])?$s3=$_GET['slider3']:$s1=0;
isset($_GET['slider4'])?$s4=$_GET['slider4']:$s1=0;
isset($_GET['slider5'])?$s5=$_GET['slider5']:$s1=0;

while ( $row = $pagedResults->fetchPagedRow())
{
    if ($page == 1 && $header) 
	{
        $header = false;
        continue;  // Skip this header row
    }
    $temp=explode(",",$row);


	$display="";
	if($temp[1]<$s1){
		$display="display:none";
	}
	elseif($temp[2]<$s2){
		$display="display:none";
	}
	elseif($temp[3]<$s3){
		$display="display:none";
	}
	elseif($temp[4]<$s4){
		$display="display:none";
	}
	elseif($temp[5]<$s5){
		$display="display:none";
	}
	
	echo '<tr style="'. $display . '"><td>';



    $row1 = str_replace( ',', "</td><td>", $row );
    echo $row1;
    echo "</td></tr>";
}
fclose($handle);
echo "</table>";

//important to set the strategy to be used before a call to fetchPagedNavigation
$pagedResults->setLayout(new DoubleBarLayout());
echo $pagedResults->fetchPagedNavigation();
//$data1 = [];
$total_columns = 0;
$handle1 = fopen('demo.csv', 'r');
while (false !== ($row = fgetcsv($handle1, 1000, ','))) {

    0 === $total_columns and $total_columns = count($row);
    $i = 0;
    while ($i <= $total_columns-1) {
	     $data1[$i][] = (int) $row[$i];
		 $i++;
	 }
}

$i = 0;

while ($i <= $total_columns-1) {

    $_SESSION["min-column-$i"] = min($data1[$i]);
    $_SESSION["max-column-$i"] = max($data1[$i]);
	$i++;
}

$_SESSION['totalcolumns'] = $total_columns;
fclose($handle1);
?>



<?php 
	  $totalcolumns = $_SESSION["totalcolumns"];
?>



<!-- Activate Simple Slider on your input -->
  <h2>Keyword Scores</h2>
  <?php
 
$i = 0;
while (++$i <= $_SESSION['totalcolumns']-1) {
isset($_GET["slider$i"]) ? $rangevalue=$_GET["slider$i"] : $rangevalue="";
    $range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
	    <br><?php echo "Keyword" ?>
	    <?php echo $i ?>
		<br><input type="text" data-slider="true" id="slider<?php echo $i; ?>" data-slider-range="<?php echo $range ?>" autocomplete="off" value="<?php echo $rangevalue; ?>" data-slider-step="1">
		<?php } ?>  



<script>
$("a").click(function(e){
	e.preventDefault();
	$passdata="";
	$passdata+="&slider1="+$("#slider1").val();
	$passdata+="&slider2="+$("#slider2").val();
	$passdata+="&slider3="+$("#slider3").val();
	$passdata+="&slider4="+$("#slider4").val();
	$passdata+="&slider5="+$("#slider5").val();
	location.href=$(this).attr("href")+$passdata;
})
</script>

<script>
var masterData=[];  

$(function() {

    $("button").on('click',function(){ loadXMLDoc(); });
    $("[data-slider]")
       .each(function (index) {
           var range;
            var input = $(this);

            $("<span>").addClass("output").attr("id","output"+index)
                .insertAfter(input);
            range = input.data("slider-range").split(",");
            $("<span>").addClass("range")
                .html(range[0])
                .insertBefore(input);
            $("<span>").addClass("range")
                .html(range[1])
                .insertAfter(input);
        })
	
        .on("slider:ready slider:changed", function (event, data) {
            var $output =$(this).nextAll(".output:first");
            $output.html(data.value.toFixed(2));
            masterData[$output.attr("id").replace(/output/,"")] = data.value;
            $("#kwBody > tr").each(function() {
               var $cells = $(this).children("td");
              
               var found=false,count=0,currentCell;
               for (var i=0;i<masterData.length;i++) {
                 currentCell=$cells.eq(i+1);
                 found = parseInt(currentCell.text(),10) >=masterData[i];
                 currentCell.toggleClass("found",found); //add or remove class to highlight 
                 count+=found;
               }
               window.console && console.log(masterData,count);
               $(this).toggle(count==masterData.length); // show if all cells >

            });
        });
});
$("slider:changed")
</script>

</body>

</html>

Open in new window


As we can see in the above code, I need to re-frame it to accomodate dynamic number of columns. (The variables $passdata and the initial isset setting needs to be modified).

This is the link to my work so far.

I am completely new to the scripting languages and I would really appreciate some help. Please let me know if you need more information.
0
Comment
Question by:ramesh4046
  • 3
  • 3
  • 3
  • +1
11 Comments
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
ID: 39602098
ramesh4046:

I added the topic PHP Scripting Language to your question in order to attract attention of more experts.

padas
Topic Advisor
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39602523
Have a look at this:

if (($handle = fopen("demo.csv", "r")) !== FALSE) {
	$firstLine = fgetcsv($handle);
	$numOfColumns = count($firstLine);
}

Open in new window

It opens the CSV file, reads the first line into an array ($firstLine) and then counts the number of elements in the array (number of columns)
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39602629
Some good "getting started" resources are available here:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

In PHP, fgetcsv() creates a numerically indexed array, with the elements numbered from zero to "n" where "n" is the count() of elements in the array minus one.
0
 

Author Comment

by:ramesh4046
ID: 39602817
Thanks for commenting out. I am using the count(row) only. I am getting the total columns count. However, I am not sure how to modify this line to accept dynamically.

isset($_GET['slider1'])?$s1=$_GET['slider1']:$s1=0;

Open in new window


I want something like,

while($j < $totalcolumns)
{
isset($_GET['slider$j'])?$s$j=$_GET['slider$j']:$s1=0;
$j++;
}

Open in new window

0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39602943
How about this:

for ($j=1; $j <= $numOfColumns ; $j++) {
	$varName = 's'.$j; //create the variable name
	$$varName = (isset($_GET["slider$j"])) ? $_GET["slider$j"] : 0;		
}

Open in new window

For variables to be parsed inside strings, they need to be in double quotes:

$_GET["slider$j"]
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39603149
Further to ChrisStanyon's point about the quotes:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12241-Quotation-Marks-in-PHP.html

It's not completely clear to me what you're trying to do, but I've done some thought-crime exercises with sliders.  One example here:
http://www.laprbass.com/RAY_temp_slider.php

<?php // RAY_temp_slider.php
error_reporting(E_ALL);


// A SEMI-GRAPHIC SLIDER TO SELECT A VALUE ON A SCALE FROM ZERO TO 100


// CREATE THE BLIVETS
$num = 0;
$blivets = NULL;
while ($num <= 100)
{
    $str = str_pad($num,3,'0',STR_PAD_LEFT);
    $blivets .= '  <div class="blivet">' . $str . '</div>' . PHP_EOL;
    $num++;
}
$blivets = trim($blivets);


// CREATE THE HTML DOCUMENT USING HEREDOC NOTATION
$htm = <<<EOD
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script>
$(document).ready(function(){

  $(".blivet").mouseenter(function(){
    $("#pick").text($(this).text());
  });

  $(".blivet").mouseout(function(){
    $("#pick").text(' ');
  });

  $(".blivet").click(function(){
    val = $(this).text();
    $("#pset").text(val);
    $("#pick").text(' ');
    val = parseInt(val);
    dat = "dat";
    $.post("RAY_temp_slider_server.php", {key:dat,val:val}, function(response){
      $("#hist p#data").html(response);
    });
  });

  $("#reset").click(function(){
    $("#pset").text('reset');
    dat = "dat";
    val = "reset";
    $.post("RAY_temp_slider_server.php", {key:dat,val:val}, function(response){
      $("#hist p#data").html(response);
    });
  });

});
</script>

<style type="text/css">
/* http://meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126 License: none (public domain) CSS RESET CSS */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
	margin: 0;
	padding: 0;
	border: 0;
	font-size: 100%;
	font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
	display: block;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}


#slider {
    background-color:green;
}

#pick {
    background-color:gainsboro;
    color:gray;
    width:2em;
    display:inline-block;
}

#pset {
    background-color:yellow;
    width:2em;
}

.blivet {
    display:inline-block;
    width:8px;
    color:transparent;
    background-color:gainsboro;
    float:left;
}
.blivet:hover {
    background-color:white;
}
#hist {
    display:block;
}
</style>

<title>Slider: Mockup on HTML5 Page in UTF-8 Encoding</title>
</head>
<body>

<span id="reset">Reset</span>
<div id="slider">

$blivets
</div>
<span id="pick"></span>
<span id="pset"></span>
<div id="hist">
<h3>History:</h3>
  <p id="data"></p>
</div>
</body>
</html>
EOD;

echo $htm;

Open in new window

On the server side of things, this:

<?php // RAY_temp_slider_server.php
error_reporting(E_ALL);
date_default_timezone_set('America/Chicago');
session_start();

// MAYBE ADD SOME SANITY CHECKS HERE?
$sig = 'Y-m-d\TH:i:s';
$key = $_POST['key'];
$val = $_POST['val'];
$now = date($sig);

// IF THE SESSION RECORD IS EMPTY
if (empty($_SESSION[$key]))
{
    $_SESSION[$key] = array();
}

// IF THIS IS A REQUEST TO CLEAR THE RECORD
if ($val == 'reset')
{
    $_SESSION[$key] = array();
}

// ADD THIS TO THE END OF THE ARRAY
$_SESSION[$key][] = array($now => $val);

// START THE OUTPUT BUFFER TO CAPTURE THE DISPLAY
ob_start();

// FORMATTED OUTPUT SHOWS REVERSE CHRONOLOGICAL ORDER OF SETTINGS
$his = array_reverse($_SESSION[$key]);
echo "<b>$key</b>:";

foreach ($his as $arr)
{
    echo PHP_EOL . '<br/>';
    foreach ($arr as $now => $val)
    {
        echo $now . ' => ' . $val;
    }
}
echo PHP_EOL;

// CAPTURE THE OUTPUT BUFFER
$res = ob_get_clean();

// SEND THE CONTENTS OF THE OUTPUT BUFFER
die($res);

Open in new window

0
 

Author Comment

by:ramesh4046
ID: 39603181
Thanks for commenting out. I have modified the initial part like you had suggested. Now, I need to modify couple of more places.

Thanks again for commenting out. This is the entire code.

<!DOCTYPE html>
<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="js/simple-slider.js"></script>
<style type="text/css">
	body {
		font-family: Verdana;
		font-size: 13px;
	}
	
	a {
		text-decoration: none;
	}
	
	a:hover {
		text-decoration: underline;
	}
</style>
<link href="css/simple-slider.css" rel="stylesheet" type="text/css" />
<link href="css/simple-slider-volume.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php 
require_once "Paginated.php";
require_once "DoubleBarLayout.php";

$names = file('demo.csv');
isset($_GET['page'])?$page = $_GET['page']:$page=1;

$pagedResults = new Paginated($names, 20, $page);
$handle = fopen('demo.csv', 'r');
  if (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
    {
    }
	 
echo "<table id='kwTable' border='4' bgcolor='#adb214' style='float:center; margin:100'>";
echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
?>
<tbody id="kwBody">
<?php
//when $row is false loop terminates
$header = true;


$total_columns = 0;
$handle1 = fopen('demo.csv', 'r');
while (false !== ($row = fgetcsv($handle1, 1000, ','))) {

    0 === $total_columns and $total_columns = count($row);
    $i = 0;
    while ($i <= $total_columns-1) {
	     $data1[$i][] = (int) $row[$i];
		 $i++;
	 }
}

$i = 0;

while ($i <= $total_columns-1) {

    $_SESSION["min-column-$i"] = min($data1[$i]);
    $_SESSION["max-column-$i"] = max($data1[$i]);
	$i++;
}

$_SESSION['totalcolumns'] = $total_columns;
fclose($handle1);


echo "I am coming here";
echo $total_columns;
if (!$page) $page = 1;
for ($j=1; $j <= $total_columns ; $j++) {
$varName = 's'.$j; //create the variable name
$$varName = (isset($_GET["slider$j"])) ? $_GET["slider$j"] : 0;
}
//isset($_GET['slider$j'])?$s.$j=$_GET['slider$j']:$s1=0;
//isset($_GET['slider2'])?$s2=$_GET['slider2']:$s1=0;
//isset($_GET['slider3'])?$s3=$_GET['slider3']:$s1=0;
//isset($_GET['slider4'])?$s4=$_GET['slider4']:$s1=0;
//isset($_GET['slider5'])?$s5=$_GET['slider5']:$s1=0;

while ( $row = $pagedResults->fetchPagedRow())
{
    if ($page == 1 && $header) 
	{
        $header = false;
        continue;  // Skip this header row
    }
    $temp=explode(",",$row);


	$display="";
	if($temp[1]<$s1){
		$display="display:none";
	}
	elseif($temp[2]<$s2){
		$display="display:none";
	}
	elseif($temp[3]<$s3){
		$display="display:none";
	}
	elseif($temp[4]<$s4){
		$display="display:none";
	}
	elseif($temp[5]<$s5){
		$display="display:none";
	}
	
	echo '<tr style="'. $display . '"><td>';



    $row1 = str_replace( ',', "</td><td>", $row );
    echo $row1;
    echo "</td></tr>";
}
fclose($handle);
echo "</table>";

//important to set the strategy to be used before a call to fetchPagedNavigation
$pagedResults->setLayout(new DoubleBarLayout());
echo $pagedResults->fetchPagedNavigation();
//$data1 = [];
?>



<?php 
	  $totalcolumns = $_SESSION["totalcolumns"];
?>



<!-- Activate Simple Slider on your input -->
  <h2>Keyword Scores</h2>
  <?php
 
$i = 0;
while (++$i <= $_SESSION['totalcolumns']-1) {
isset($_GET["slider$i"]) ? $rangevalue=$_GET["slider$i"] : $rangevalue="";
    $range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
	    <br><?php echo "Keyword" ?>
	    <?php echo $i ?>
		<br><input type="text" data-slider="true" id="slider<?php echo $i; ?>" data-slider-range="<?php echo $range ?>" autocomplete="off" value="<?php echo $rangevalue; ?>" data-slider-step="1">
		<?php } ?>  



<script>
$("a").click(function(e){
	e.preventDefault();
	$passdata="";
	$passdata+="&slider1="+$("#slider1").val();
	$passdata+="&slider2="+$("#slider2").val();
	$passdata+="&slider3="+$("#slider3").val();
	$passdata+="&slider4="+$("#slider4").val();
	$passdata+="&slider5="+$("#slider5").val();
	location.href=$(this).attr("href")+$passdata;
})
</script>

<script>
var masterData=[];  

$(function() {

    $("button").on('click',function(){ loadXMLDoc(); });
    $("[data-slider]")
       .each(function (index) {
           var range;
            var input = $(this);

            $("<span>").addClass("output").attr("id","output"+index)
                .insertAfter(input);
            range = input.data("slider-range").split(",");
            $("<span>").addClass("range")
                .html(range[0])
                .insertBefore(input);
            $("<span>").addClass("range")
                .html(range[1])
                .insertAfter(input);
        })
	
        .on("slider:ready slider:changed", function (event, data) {
            var $output =$(this).nextAll(".output:first");
            $output.html(data.value.toFixed(2));
            masterData[$output.attr("id").replace(/output/,"")] = data.value;
            $("#kwBody > tr").each(function() {
               var $cells = $(this).children("td");
              
               var found=false,count=0,currentCell;
               for (var i=0;i<masterData.length;i++) {
                 currentCell=$cells.eq(i+1);
                 found = parseInt(currentCell.text(),10) >=masterData[i];
                 currentCell.toggleClass("found",found); //add or remove class to highlight 
                 count+=found;
               }
               window.console && console.log(masterData,count);
               $(this).toggle(count==masterData.length); // show if all cells >

            });
        });
});
$("slider:changed")
</script>

</body>

</html>

Open in new window


I need to modify the variables in the below places too. I am not sure on how to do it.

if($temp[1]<$s1){
		$display="display:none";
	}
	elseif($temp[2]<$s2){
		$display="display:none";
	}
	elseif($temp[3]<$s3){
		$display="display:none";
	}
	elseif($temp[4]<$s4){
		$display="display:none";
	}
	elseif($temp[5]<$s5){
		$display="display:none";
	}

Open in new window


And also, another part where I need to modify is here.
<script>
$("a").click(function(e){
	e.preventDefault();
	$passdata="";
	$passdata+="&slider1="+$("#slider1").val();
	$passdata+="&slider2="+$("#slider2").val();
	$passdata+="&slider3="+$("#slider3").val();
	$passdata+="&slider4="+$("#slider4").val();
	$passdata+="&slider5="+$("#slider5").val();
	location.href=$(this).attr("href")+$passdata;
})
</script>

Open in new window


Can you please guide me out?
0
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 39603234
This is starting to resemble a development request, rather than a question, and the logic in your code is somewhat 'scattered' to say the least (and flat -out broken in places). It's nearly impossible to follow.

Assuming you have a variable containing the columnCount, this will create your passdata:

<script>
$("a").click(function(e){
	e.preventDefault();
	$passdata = "";

	<?php
	for ($i=1; $i <= $columnCount ; $i++) { 
		printf('$passdata+="&slider%d="+$("#slider%d").val();' . PHP_EOL, $i, $i);
	}
	?>
	
	location.href=$(this).attr("href")+$passdata;
})
</script>

Open in new window

As for your 'if' statement, you're saying that if any of the temp[] variables are less than their counterpart, then set the $display variable to display:none! Here you go:

for ($i=1; $i <= $columnCount; $i++) { 
	$varName = 's'.$i; 
	if ($temp[$i] < $$varName) $display = "display:none";
}

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39603237
One possible approach to this might be to tell us in plain language what you want the web page to do.  Nothing technical, just a description.  With that and the data set, we ought to be able to show you some kind of design pattern that would be useful.
0
 

Author Comment

by:ramesh4046
ID: 39603254
Sorry for the confusion. I will describe briefly what am trying to do.

- I have a CSV file coming from different source (I don't know anything about the file beforehand).

- Once the file arrives, I need to display the CSV file in a paginated format.

- I will also be having the range sliders in my web page based on the total columns of my CSV file. So, for example, if my CSV file contains 5 columns, I will be having 5 UI sliders with the slider range set as the min and max of each column. (If you see the page, you can understand more what am trying to say).

- If the user selects some range values, I need to display only the rows satisfying the criteria.

So, basically I am trying to update the display based on the range selection.

Please let me know if you need more information.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

This article will show, step by step, how to integrate R code into a R Sweave document
Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now