Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a table full of band listings for our Musician Finder program. We want to sort them by genre while still only having one .html or .php file containing all the information.
How would I even start to do this? Preferably with php and avoiding JS because most of our users have noscripts.
Here is a link to the test page HERE. Any suggestions would be great or even just an example of where someone else has done it.
And here is the table on paste bin.
Thanks
Also, avoiding SQL is a priority to my boss.
EDIT: So apparently this isn't feasible in php. I'd be willing to use javascript. Or Jquery. If this was just a simple table I'd be fine but obviously mine is more detailed and I don't know where to start and haven't found anything on google. If anyone wants to kindly suggest anything about this that'd be great but honestly nobody comes on here to read about how someone else doesn't like that I asked a question on stackoverflow. Lol.
EDIT AGAIN: Ok so I was looking more... And why can't I just make all my <tr>'s have display:block; per class in css, then use a JS function to change all but the right class to display:none;? This would be extremely simple.
#robert is correct as you can't sort elements on the page without using some javascript. so if you want to sort your table with php, you have to start by putting the contents of your table into data set of some sort, like a large array. from what i understand of what you're looking to do is that every row of your table falls into one of your sortable categories. so then when defining your array, you have to specify what category each row falls under and then sort on that field.
so your array definition could be something like this:
$master_array[] = array(
'category' => 'acoustic',
'tr_html' => '<tr><td> .... </td></tr>'
);
then sort the array on the category field. a bit of googling will help you with this.
then when it comes to writing the table, just do:
echo "<table>";
foreach( $master_array as $key => $val ) {
echo $val["tr_html"];
}
echo "</table>";
hope this helps...
If you create a 'Table' object in php, with a $tbl = array(0 => $arr_row1, 1 => $arr_row2) etc. property, then you can easily create a view method to render the $tbl in html using a loop. (All $arr_rowx are associative arrays with the same column names as keys.)
Then you can use this method to order or reverse order $tbl on a string column key:
public function order($str_key_name, $bool_reverse = false) {
$code = "return strnatcmp(\$a['$str_key_name'], \$b['$str_key_name']);";
usort($this->tbl, create_function('$a,$b', $code));
if ($bool_reverse) $this->tbl = array_reverse($this->tbl);
return $this->tbl;
}
and to re-index sequentially on an integer column:
public function reIndex($str_index_name, $int_start_index = 0) {
if ($this->tbl) {
$num = count($this->tbl);
for ($i = 0; $i < $num; $i++)
$this->tbl[$i][$str_index_name] = ($i + $int_start_index);
}
return $this->tbl;
}
Using an existing table plugin in JavaScript would probably be the best solution for you since it would avoid the round trip back to the server to do something that JavaScript can do quite easily. But seeing that you say that JavaScript is not your first option then you can do it in PHP if you choose to store all the data in a PHP array.
So you start by putting all the data into PHP arrays. Then write a function that will sort the array by whichever field you wish. There are many sorting algirithms available for this.
Display the table of data in its default order and add links that will let the user select a different column to sort. In each link you set the name of the column to sort by like this:
Sort By Name
You can then simply use the parameter "sort" to decide how to sort your array before you echo it out into an HTML table.
I ended up using jquery. Anyone that doesn't have JS on just won't be able to sort haha. Thanks for the suggestions guys.
Related
I am using php as backend of a website. I made a form of around 50 questions and I have to store it in a table every single time I answer something different.
So my first newbie thought was to compare the $request->Question1 with the $table->Question1 and if this is different, I create a new record on the History table.
But it took my to an endless and nothing good looking comparison lines, repeating some of the code like:
if ($table->Question1 != $request->Question1)
{
$Question = new HistoryTable();
$Question ->reason = 'Change Answer';
$Question ->column_affected = 'Question1';
$Question ->old_value = $table->Question1;
$Question ->new_value = $request->Question1;
$Question ->created_at = Carbon::now();
$Question ->save();
}
Is there a way it could be reduced ? I was thinking in using a form, but I have to mention I have columns/values as Question23_1 and Question23_2 ... but they are the same name as in table
Thanks in advance!
Well, some might suggest a different database-table architecture – one that does not involve these "repeating groups." But there might be other compelling reasons to have done what you did.
Maybe you could retrieve the record, instead of as a "PHP object," as an array ("hash" ...) indexed by field-name. Then you could use interpolation of strings such as "Question$x_$y" ... substituting the values of $x and $y to obtain the name of the field whose value you are now interested in ...
I have a quick question regarding php, lets say I had something like this:
<?php
$rightcolors = Array();
$leftcolors = Array();
$rightcolors[]="Yellow";
$leftcolors[]="Violet";
$rightcolors[]="Yellow Green";
$leftcolors[]="Red Violet";
$rightcolors[]="Green";
$leftcolors[]="Red";
$rightcolors[]="Blue Green";
$leftcolors[]="Red Orange";
$rightcolors[]="Blue";
$leftcolors[]="Orange";
$rightcolors[]="Blue Violet";
$leftcolors[]="Yellow Orange";
?>
But I want to not have array that contains different things, I rather want to label them separately like so:
<?php
$left="Green"
$leftcorrect="Yellow"
$blu="Blue"
$blucorrect="blu"
?>
Would it be appropriate to still use an array even though it only contains values? I am assuming this is not the correct way to do this and a lot of questions would involve a lot of different arrays which is not convenient. In that case would be the second list of little code with the different names be fine? The reason for this is before I was using arrays to allow the quiz to randomly ask one question, now I want to make a quiz that pulls very specific questions.
I've been searching for a while now to accomplish my question, so I decided to ask it here.
My problem.
I've filled 2 arrays with content from a database like this:
$query = "SELECT table_1, table_2 FROM questions";
// Execute query or trow an error
$results = mysqli_query($conn, $query) or die(mysql_error());
$resulttablet1= array();
$resulttablet2= array();
while($row = mysqli_fetch_array($results))
{
// Add the right questions to the array
$resulttablet1[] = $row['table_1'];
$resulttablet2[] = $row['table_2'];
}
So I've now got 2 arrays, each filled with the content of one table. This is all working fine. Now I want to put those two arrays into one array so it acts like one big array.
Something like this:
$newarray = array();
$newarray[$resulttablet1, $resulttablet2];
or
$newarray = array($resulttablet1,
$resulttablet2);
Then I want to echo $newarray and show all the elements of the other two arrays.
I know I can echo both arrays separately, but this is not possible for the goal I'm trying to accomplish.
Thanks in advance.
Edit
I realise my question isn't clear enough, I'll try to explain it a bit better.
On top of my question I want to show the the content of both arrays one by one on button click. That's what I'm doing at the moment like this:
// I retrieve a value from a javascript file, where I add 1 to a variable each time a button is clicked then I send this value to the server using jQuery Ajax
$value = (int)$_POST["question_nmbr"];
// I use $value to echo the right element out of the array.
echo "<li>$resulttablet1[$value]</li>";
Everytime the button is clicked ajax loads the php file and the value is increased so the next question is loaded.
I want to do the same thing but now with an array which has multiple arrays inside of it.
array_merge doesn't do the trick I think, cause print_r($result); gives me all the content of the array.
I hope my question is a little bit more clear now.
I found the answer, thanks to someone who removed his answer already.
array_merge did the trick after all, I don't know what I did wrong the first time but now I can echo it just fine.
Here is how it works:
// I retrieve a value from a javascript file, where I add 1 to a variable each time a button is clicked then I send this value to the server using jQuery Ajax
$value = (int)$_POST["question_nmbr"];
$newarray = array_merge($resulttablet1, $resulttablet2);
echo "<li>$newarray[$value]</li>";
Hope someone will find this useful, if not ask for more info :)
I am writing an application in PHP where users can enter two sets of information and have every possible combination of the two sets printed out. The goal is to use it as a teaching tool for learning language by practicing different patterns of a question and answer.
For example, we may practice the question "Have you ever tried...?" plus one of four activities, such as bungee jumping, para sailing, skydiving, and scuba diving. There would also be four possible answers:
Yes I have, and I enjoyed it.
Yes I have, but I didn't like it.
No I haven't, but I want to try it.
No I haven't, and I don't want to try it.
The user would input the two sets of data, and the application would then print sheets of cards containing all possible combinations of the questions and answers. For example, card 1 would look like this:
skydiving: Yes I have, and I enjoyed it.
scuba diving: Yes I have, but I didn't like it.
parasailing: No I haven't, but I want to try it.
bungee jumping: No I haven't, and I don't want to try it.
The next card might then look like this:
skydiving: Yes I have, but I didn't like it.
scuba diving: No I haven't, but I want to try it.
parasailing: No I haven't, and I don't want to try it.
bungee jumping: Yes I have, and I liked it.
So as you can see, there are many different possible combinations. The idea would be that both lists would be of the same length to allow all of the possibilities to be printed out. It is also important that no question or answer gets used more than once on any card, and that two cards can be alike. What would be the best way to go about this? The actual input and output is not the problem--I've done similar things before. I just need the algorithm to produce the combinations.
EDIT: I guess what I'm really after is to keep the activities in the same order for each card, but have every possible combinations of answers. So what I really need is to be able to produce the following set of indexes for getting data out of the answers array. So I really want something more like this:
0,1,2,3
0,1,3,2
0,2,1,3
0,2,3,1
0,3,1,2
0,3,2,1
1,0,2,3
1,0,3,2
1,2,0,3
1,2,3,0
...and so on until all possible combinations have been produced.
Try this:
$activities = array(); // Input all your activities as elements here.
$responses = array(); // Input all your responses as elements here.
foreach ($activities as $activity) {
foreach ($responses as $response) {
echo $activities.' '.$response."\n";
}
}
OK, with the new criteria, I think I understand a little better.
Try recursion. My solution is messy as hell but I can walk you through it:
$activities = array('a', 'b', 'c', 'd'); // Input all your activities as elements here.
$responses = array(1, 2, 3, 4); // Input all your responses as elements here.
// Recursive function outputCombos accepts both arrays (for eventual output).
// $workingArray is the array of the current branch we're working with.
function outputCombos ($activities, $responses, $workingArray) {
// Once the working array has been loaded to the maximum amt, print everything out.
if (count($workingArray) == count($responses)) {
echo "Combo\n";
for ($x = 0; $x < count($activities); $x++) {
echo $activities[$x].'::'.$workingArray[$x]."\n";
}
// If the working array isn't full, add an element that isn't currently in the working array, and recursively run the function again.
} else {
foreach ($responses as $response) {
// Iterate through list of all possible responses, add it into a new working array and run the function if the response hasn't been used in this working array.
if (!in_array($response, $workingArray)) {
$newArray = $workingArray;
$newArray[] = $response;
outputCombos($activities, $responses, $newArray);
}
}
}
}
foreach ($responses as $response) {
echo '<pre>';
// Start each branch of tree with unique response (should be 4 in this case).
outputCombos($activities, $responses, array($response));
echo '</pre>';
}
Trying to sort an array in PHP that is being populated from a CSV. I would also, ideally, LOVE to be able to control the sort by clicking on tabs in the table here .. Right now, though, my first task at hand is just sorting the damn thing.. been working on this for over 3 days now.. any help is GREATLY appreciated!! Cheers!
PHP
<?php
$fp = fopen("https://spreadsheets.google.com/pub?key=0AjZgwY03sLMGdHVoWjhucGowWWJBb2g2NnQzVG9HZFE&hl=en&single=true&gid=0&output=csv","r");
$rows = array();
while (($row = fgetcsv($fp)) !== FALSE) {
$rows[] = $row;
}
fclose($fp);
$headers = array_shift($rows);
foreach ($rows as $row) : list($ShowKey, $ShowFeedURL, $ShowLink, $ShowIcon, $ShowTitle, $ShowTag, $ShowCategory, $ShowEps, $ShowLastUpdate, $ShowNew) = $row;
$oddpost = ( empty( $oddpost ) ) ? '_odd' : ''; ?>
I recently did this. I had a multi-dimensional array of records from a database, and I needed to sort them based off of one specific column in the array. Here's what I did:
foreach($TimeRecords as $key => $value)
{
$Rates[$key] = $value['rate'];
}
array_multisort($Rates, SORT_ASC, $TimeRecords);
I build an array of only the column I need, then I use the array_multisort() function to sort the array based off of that column.
You can write functions that will do this in PHP and then just call them with javascript ajax calls and reload that part of the page when it's done sorting.
Instead of sorting the table in PHP, you may consider doing it client-side in Javascript. For instance have a look at this jQuery plugin: http://tablesorter.com/
You may find usort() function helpful. It accepts callback argument, which may be used for sorting by specific field.
I had a similar issue to this today. Basically what I ended up doing is creating a temporary table which I loaded in the rows from the csv file that I needed. From there, I used php to sort and organize the data and update or add to the table I needed to alter.
Example, I made a table called 'temp' and loaded in all the rows of the category I needed. Then, once this was in the table, I made a php script which sorted the information by number of total sales in descending order. From there, I did a query to update my main table and used a limit to control this (only the top 200 items by number of sales).
It was very easy to do and hopefully it will help you or someone else.
Keep in mind. If you're going to do this more than once, you will need to truncate the temporary table to remove the old rows first.