Reputation: 759
I have a table with books informations and the user must have the option to sort the table as he wish.
There are three options:
Author, Title, Edition
all they can be ASCENDING or DESCENDING.
But there is no order in that selection. The user can select: Title ASC and Edition DESC or Author DESC and Edition ASC and Title DESC or even just Edition ASC.
The question is. Which way is better to create this in PHP? By Forms? Arrays? How can i suppose to manage this information to be like this?
{"Author" => "Desc", "Title" => "Asc"}
I've already got the sorting script, i just need to understand how can i manage customized information like this way. I think arrays would be better but how can i pass through Forms?
I've tried to figure out but all solutions i though are ugly and have a poor code.
Here's a picture of the service just for those who did not understand:
Here's basically the code of everything until now:
<?php
$file = file_get_contents('books.json');
$json = json_decode($file, true);
$json = array_map(function($a) { return $a['book'][0]; }, $json['books']);
foreach ($json as $key => $row):
$title[$key] = $row['Title'];
$author[$key] = $row['Author'];
$edition[$key] = $row['Edition'];
endforeach;
array_multisort($title, SORT_ASC, $author, SORT_ASC, $json); // This is the default
?>
<form method="post">
<table align="center">
<tr>
<td>
Sort By
</td>
<td>
Direction
</td>
</tr>
<tr>
<td>
<select class="select" id="firstRule" name="firstRule">
<option value="">Select</option>
<option value="Author">Author</option>
<option value="Title">Title</option>
<option value="Edition">Edition</option>
</select>
</td>
<td>
<select id="firstRuleOrder" name="firstRuleOrder">
<option value="">Select</option>
<option value="up">Ascendent</option>
<option value="down">Descendent</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit">
</td>
</tr>
</table>
</form>
Upvotes: 1
Views: 75
Reputation: 24551
Instead of "firstRule" and "firstRuleOrder" the dropdowns should be named "rule[0]" and "ruleOrder[0]". Then duplicate them with increasing array indexes (you can do that with JavaScript or just show as many as there are columns).
To construct your call to array_multisort
, you will have to iterate over $_POST['rule']
and $_POST['ruleOrder']
and create an array of arguments. The actual function call then happens with call_user_func_array
(that's necessary because you don't know the number of arguments in advance)
Upvotes: 1