I have an html table that is populated from a text file, formatted and semi colon separated.
I would like the user to have the option of sorting alphabetically with either of the columns when clicking on the column name (header).
How do I do this in php?? Or is there another way of doing this? Thanks for your help.
Sample raw data/input looks like this:
TYPE=abc;PART=georgetown;FILE=goog_abc.dat.2010122211.gz
TYPE=xyz;PART=ucny;FILE=aol_xyz.dat.2010122209.gz
Php code for table:
$lines = preg_split('~\s*[\r\n]+\s*~', file_get_contents('/temp/tab.txt'));
foreach($lines as $i => $line) {
$pairs = explode(';', $line);
foreach($pairs as $pair) {
list($column, $value) = explode('=', $pair, 2);
$columns[$column] = true;
$rows[$i][$column] = $value;
}
}
$columns = array_keys($columns);
echo '<table><thead><tr>';
foreach($columns as $column) {
echo '<th>'.$column.'</th>';
}
echo '</tr></thead><tbody>';
foreach ($rows as $row) {
echo '<tr>';
foreach($columns as $column){
echo '<td>'.$row[$column].'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
I'd recommend using some jQuery. In fact, this looks like exactly what you need.
Edit Put this in between your <head> tags
<script type="text/javascript">
$(document).ready(function()
{
$("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} );
}
);
</script>
Or you can put it in a separate file and link it like this. (Probably only do this if you intend to write more javascript.
<script type="text/javascript" src="path/to/file.js"></script>
Use something javascript based to sort the table after you draw it. Trying to add this kind of sorting from within PHP is painful and not needed unless you have multiple pages of data (then you need PHP to sort it in the database side). Here is a list that gives you a LOT of options for sortable tables - you should be able to apply many of those to your table after you generate it using PHP.
http://www.webdesignbooth.com/15-great-jquery-plugins-for-better-table-manipulation/
Related
i have made some random input names, because its a drag and drop page builder, so i can't guess, how much elements user will use, so i have created a random input names,
for that am using php foreach loop for $_POST requests. i have tried to make it encoded into json and then later save it into database. but it looks like something is wrong in my json.
Here are my html demo codes :
<input style="display:none;" name="DATA-BLOCK-A(some random string)">
<input style="display:none;" name="DATA-BLOCK-B(some random string)">
PS: A is for selecting element A, and B is for element B.
here is my PHP code :
if (isset($_POST)) {
//$arr = array();
foreach($_POST as $key => $value)
{
$arr = array($key => $value);
$encode = json_encode($arr);
echo $encode;
}
}
and Here is the result :
{"sortlist":"block[]=D5e3385b75a75d&block[]=K5e3385b85a75e&block[]=C5e3385b95a75f&block[]=F5e3385ba5a760"}{"save_cont_flag":"0"}{"DATA-block-D5e3385b75a75d":"0#TRANSP
<\/p>"}{"DATA-block-K5e3385b85a75e":"0#TRANSP20"}{"DATA-block-C5e3385b95a75f":"01#TRANSP0images\/250place.jpg\u00b8"}{"text-1573532276681":""}{"textarea-1573532278320":""}{"DATA-block-F5e3385ba5a760":"121212unundefined"}{"page_name":"123"}{"aff_link":""}{"pause_link":""}{"seo_title":""}{"fbook":""}{"seo_desc":""}{"seo_keywords":""}{"back_color":"#EEEEEE"}{"body_color":"#FFFFFF"}{"back_image":""}{"ty_font_color":"#000000"}{"ty_override":""}{"ty_name":"12314"}{"ty_stm":""}{"modal_para_width":"0"}{"catcha_url":""}{"catcha_un":"Yes"}{"catcha_message":""}{"code_head":""}{"code_body":""}{"modal_share_width":"0"}{"modal_cta_width":"0"}{"modal_video_width":"0"}{"modal_mp_width":"0"}{"modal_stm_width":"0"}{"modal_image_width":"0"}{"modal_bonus_width":"1"}{"ty_headline":""}{"modal_spacer_width":"0"}{"att_bar_status":"0"}{"att_delay_in":"0"}{"att_bar_color":"#bbbbbb"}{"att_gradient":"0"}{"att_text_color":"#000000"}{"att_text_font":"Open Sans:400"}{"att_text_size":"14"}{"att_bar_message":"Add Your Attention Bar Text Here"}{"att_link_color":"#000000"}{"att_link_label":"Add Link Text Here"}{"att_link_url":"http:\/\/commissiongorilla.com"}{"count_font":"Open Sans:800"}{"count_size":"55"}{"count_status":"0"}{"count_type":"0"}{"count_end":"01\/31\/2020 6:41 AM"}{"count_zone":"0.0"}{"count_eg_days":"0"}{"count_eg_hours":"0"}{"count_eg_mins":"0"}{"count_digit_color":"#bbbbbb"}{"count_label_color":"#bbbbbb"}{"count_background":"0"}{"count_language":"1"}{"count_exp":"0"}{"count_url":"http:\/\/commissiongorilla.com"}{"count_add_days":"0"}{"count_add_hours":"0"}{"count_add_mins":"0"}{"modal_countdown_width":"0"}{"modal_review_width":"0"}
and also how seperate all A BLOCKS and B BLOCKS?
Thanks.!
You don't need to use a loop.
Just used json_encode :
$json = json_encode($_POST);
If you need to get key contain DATA-block-, you can write :
foreach ($_POST as $key => $value) {
if (strpos($key, 'DATA-block-') !== false) {
// Here `DATA-block-{}`
}
}
If you change the input names to DATA-BLOCK-A[] and DATA-BLOCK-B[], $_POST['DATA-BLOCK-A'] will contain an array of all a blocks and $_POST['DATA-BLOCK-B'] will contain an array of all b blocks.
This also eliminates the need for generating random strings.
I am selecting multiple values that I export from google sheet.
I need to make them independent of filtering them in ACF so that they can be filtered separately.
I show code that I'm trying to use in functions.php but I do not know where I'm wrong:
$value=get_field('location'); //location is my custom field that I am exporting from google sheet
$arrFields= explode(", ",$value);
if( $value)
{
foreach($arrFields as $v){ echo $v.'<br>'; };
}
Meta Keys Select will be automatically modified? this is what the filter takes
thanks!!
You are not checking whether it is array or not
$value=get_field('location');
$arrFields= explode(", ",$value);
if( is_array($arrFields))
{
foreach($arrFields as $k=>$v)
{
echo $k.'- '.$v.'<br>';
}
}
You can use implode instead of foreach
http://php.net/manual/en/function.implode.php
I'm becoming a little frustrated with my array results. Ideally, I am creating a form maker module within my application and I am working with two different arrays to establish my database columns and excel columns. Essentially, I am using the results provided by the arrays to write directly to a php file (Excel reader file). In order to establish a difference in Excel Workbooks, I am putting forth an identifier "page2","page3" and so on within the "excel_rows" array.
//my arrays
$table_columns = array('field1','field2','field3','field4','field5'); //fields
$excel_rows = array('c1','c2','page2','c3','c4','page3','c5'); //excel columns
From here.. I go on to try to filter the array keys..
foreach(array_keys($excel_rows) as $key){
$page = array_search(strpos(trim($excel_rows[$key]),'page'),$excel_rows);
if(strpos(trim($excel_rows[$key]),'page') !== false){
$excel_row .= '$objTpl->setActiveSheetIndex('.(str_replace('page','',trim($excel_rows[$key])) -1).');<br/>'.PHP_EOL;
$table_columns[$key] = 0;
}
else {
$excel_row .= '$objTpl->getActiveSheet()->setCellValue(\''.trim($excel_rows[$key]).'\',$row[\''.trim($table_columns[$key]).'\']);<br/>'.PHP_EOL;
}
}
print $excel_row;
The result should echo out the following:
$objTpl->getActiveSheet()->setCellValue('c1', $row['field1']);
$objTpl->getActiveSheet()->setCellValue('c2', $row['field2']);
$objTpl->setActiveSheetIndex(1);<br/>
$objTpl->getActiveSheet()->setCellValue('c3', $row['field4']);
$objTpl->getActiveSheet()->setCellValue('c4', $row['field5']);
$objTpl->setActiveSheetIndex(2);
$objTpl->getActiveSheet()->setCellValue('c5', $row['']);
As one can see, I am missing 'field3' from my result and 'cs' produces and empty row rather than "field5".
I'm assuming something like array_compare or array_combine is the solution - I'm just not able to put it together.
Everything works lovely with module pardoning the array code above. Any help with this would be sincerely appreciated!
-Regards.
How it currently is I'd say you need to set an integer +1 whenever you create a new page and then subtract that integer from the key so you can get the right field.
$subkey = 0;
foreach(array_keys($excel_rows) as $key){
$fieldkey = $key - $subkey;
$page = array_search(strpos(trim($excel_rows[$key]),'page'),$excel_rows);
if(strpos(trim($excel_rows[$key]),'page') !== false){
$excel_row .= '$objTpl->setActiveSheetIndex('.(str_replace('page','',trim($excel_rows[$key])) -1).');<br/>'.PHP_EOL;
//$table_columns[$key] = 0; I'm not sure what this is supposed to do
$subkey++;
}
else {
$excel_row .= '$objTpl->getActiveSheet()->setCellValue(\''.trim($excel_rows[$key]).'\',$row[\''.trim($table_columns[$fieldkey]).'\']);<br/>'.PHP_EOL;
}
}
print $excel_row;
I have to sort the file data in a table depending on how the user chooses it to be sorted (only options are ascending and descending)
Here is my code for it:
if($submit=="Display"){
if ($headings=="0"){echo "<h2>Error</h2>";}
elseif ($search==""){echo "<h2>Error</h2>";}
else {
if($headings==$headings_array[0])
echo "<table border='1'>";
$f = fopen("data.csv", "r");
while ($line = fgetcsv($f)){
echo "<tr>";
foreach ($line as $cell) {
echo "<td><center>".$cell."</center></td>";
}
echo "<tr>";
}
fclose($f);
function my_sort($a, $b){
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}
$arr = $cell;
usort($arr, "my_sort");
print_r ($arr);
echo "</table>";
}
}
But it's not sorting. Can someone spot what's wrong with it? And if you have a more efficient way of doing this, please let me know as I have 15 headings and it would be a pain to do if statements for each of those headings.
To be clear, here is what I have to do:
For each sort field (which are the headings) that the user chooses, I have to arrange the display according to that heading
i.e if($headings==$headings_array[0])
$headings_array[0] is equal to Names therefore, the table should display the values in alphabetical (or reverse alphabetical) order of Names
Extra info:
$headings is the name of the select box
$headings_array is the array values for the select box
$search is the radio buttons containing whether the table should be sorted as ascending or descending
PHP only
Any help is appreciated!
I think your sort function is wrong. It's doing the same thing as sort() or rsort() would do.
usort simply compares two array elements and determines if they need to be swapped based on the value you return. Your sending in $a and $b, which should be csv lines. Then you compare the indexes that you need to and swap the lines accordingly.
You need to have it sort by the array index given by heading. maybe try something like this:
global $headings;
...
$arrayToBeSorted = array();
// send in an array of lines
while ($line = fgetcsv($f)){
$arrayToBeSorted[] = $line;
}
usort($arrayToBeSorted, 'my_sort');
function my_sort($lineA, $lineB){
// set this to the column that needs to be sorted
global $headings;
$linePartsA = explode(',' $lineA);
$linePartsB = explode(',' $lineB);
if ($linePartsA[$headings] == $linePartsB[$heading) return 0;
return ($linePartsA[$headings] > $linePartsB[$heading]) ? -1 : 1;
}
}
Why do you want to use php only . I used jquery table sorter which is very efficient .here is the link table sorter
Let's say I am getting requests such as:
http://www.example.com/index.php?id=123&version=3&id=234&version=4
Is it possible to extract these in a simple way inside my php code? I realize I could get the entire querystring with javascript using window.location.href and handle it manually but I'm looking for something more elegant. The requests can contain any number of version/id pairs but I can assume that the query is well-formed and have no obligation to handle invalid strings.
If you can change the field name to include [], then PHP will create an array containing all of the matching values:
http://www.example.com/index.php?id[]=123&version[]=3&id[]=234&version[]=4
If you don't have the ability to change the field names, then as you say, you'll have to parse the querystring yourself.
According to this comment from the PHP manual, PHP's query string parser will drop duplicate params... so I don't think that PHP is a good fit for what you want to do (except in that it has the same capacity as javascript to get the raw query string, with which you can do whatever you want)
Assuming you have some control over the request, suffix the name with [] and PHP will generate arrays instead of dropping all but one.
http://www.example.com/index.php?id[]=123&version[]=3&id[]=234&version[]=4
Since they are pairs you'll probably want to fix the order they appear in using indexes.
http://www.example.com/index.php?id[0]=123&version[0]=3&id[1]=234&version[1]=4
Just extract the keys and values of $_GET, use the function as:
print_array('$_GET...',$_GET);
... and the function code will be:
function print_array($title, $arr) {
echo '<table width="100%" style="padding:10;">';
echo '<tr><td width="30%" style="text-align:right; background-color:bisque;">key of </td><td style="background-color:bisque;">'.$title.'</td></tr>';
foreach($arr as $key => $value) {
echo '<tr>';
echo '<td style="text-align:right; color:grey;">';
echo $key;
echo '</td>';
echo '<td>';
echo $value;
echo '</td>';
echo '</tr>';
}
echo '</table>';
}
Not as rounded or reliable as methods mentioned above but I use this to remove the need to [] in urls without worrying about rewriting.
$aQuery = explode("&", $_SERVER['QUERY_STRING']);
$aQueryOutput = array();
foreach ($aQuery as $param) {
if(!empty($param)){
$aTemp = explode('=', $param, 2);
if(isset($aTemp[1]) && $aTemp[1] !== ""){
list($name, $value) = explode('=', $param, 2);
$aQueryOutput[ strtolower(urldecode($name)) ][] = urldecode(preg_replace('/[^a-z 0-9\'+-]/i', "", $value));
}
}
}