The function works well for creating a formatted table from a multi-dimensional array and assigning it to a variable. When there is a sub-array it will nest another table nicely but instead, i'd like to display a comma-separated list (conditional only for sub-arrays).
What php function / logic could help me accomplish this and how should I implement it?
It currently displays this...
<table>
<tr>
<td><span style="color:#ffeeee;">Keywords</span></td>
<td>
<span style="color:#eeeeff;">
<table>
<tr>
<td><span style="color:#ccffcc;">Alex</span></td>
</tr>
<tr>
<td><span style="color:#ccffcc;">Mic</span></td>
</tr>
<tr>
<td><span style="color:#ccffcc;">snowboarding</span></td>
</tr>
</table>
</span>
</td>
</tr>
</table>
Would prefer something like this...
<table>
<tr>
<td><span style="color:#ffeeee;">Keywords</span></td>
<td><span style="color:#eeeeff;">Alex, Mic, snowboarding</span></td>
</tr>
</table>
PHP Code (display_array_processor.php):
//----------------------------------------------------//
/*
// Iterating complex php multidimensional multi-level array
// to html table using return instead of echo
*/
//----------------------------------------------------//
if($_POST)
{
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
$process_method = $_POST["process_method"];
$process_levels = $_POST["process_levels"];
//Sanitize input data using PHP filter_var()
//$process_method = filter_var($_POST["process_method"], FILTER_SANITIZE_STRING);
//----------------------------------------------------//
if ($process_levels == "noheaders") {
// Sample array from shell command (No Headings)...
$myArray = array(
array(
"Size" => "914 kB",
"Date" => "2015:02:08 18:01:00-08:00",
"Attributes" => "Regular; (none)",
"Names" =>
array(
"Alex Smith",
"Mike Jones"
),
"Keywords" =>
array(
2015,
"Alex",
"Mike",
"snowboarding",
array(
'A snow',
'B cold',
'C fun'
)
),
"Software" => "Invisible Space-Monkey Monitoring System 01",
"Duration" => 4800
)
);
} elseif ($process_levels == "headers") {
// Sample array from shell command (With Headings)...
$myArray = array(
array(
"SourceFile" => "test.txt",
"Tool" =>
array(
"Version" => 11.12
),
"File" =>
array(
"Size" => "104 kB",
"ModifyDate" => "2016:02:08 18:01:00-08:00"
),
"Region" =>
array(
"RegionAppliedToDimensionsUnit" => "pixel",
"RegionName" =>
array(
"Alex Smith",
"Mike Jones"
),
"Subject" =>
array(
2015,
"Alex",
"Mike",
"snowboarding"
)
)
)
);
} else {
// Small Sample Array...
$myArray = array(
"Source" => "test.txt"
);
}
if ($process_method == "tables") {
//$html = recursive_array($myArray);
$html = recursive_array_table($myArray);
} elseif ($process_method == "commas") {
$html = array_table($myArray);
} else {
$html = "Do not know the process method.";
}
//$html .= '<p><textarea rows="10" cols="75">'.$process_method.'</textarea></p>';
$output = json_encode(array('type'=>'message', 'text' => $html));
die($output);
}
//----------------------------------------------------//
// Recursive Array Functions - COMMA SUB-ARRAYS
//----------------------------------------------------//
// Two generic utility functions:
function is_nested($array) {
return is_array($array) && count($array) < count($array, COUNT_RECURSIVE);
}
function is_assoc($array) {
return is_array($array) && array_keys($array) !== range(0, count($array) - 1);
}
function array_table_row($key, $row) {
$content = array_table($row);
return "<tr>\n<th>$key</th>\n<td>$content</td>\n</tr>\n";
}
function array_table($array) {
if (is_nested($array) || is_assoc($array)) {
$content = implode("", array_map('array_table_row', array_keys($array), $array));
return "<table border=1>\n<tbody>\n$content</tbody>\n</table>\n";
}
// At this point $array is too simple for a table format:
$color = is_array($array) ? "922" : "292";
$content = htmlspecialchars(is_array($array) ? implode(", ", $array) : $array);
return "<span style='color:#$color'>$content</span>";
}
//----------------------------------------------------//
// Recursive Array Functions - TABLE SUB-ARRAYS (ORIG)
//----------------------------------------------------//
function recursive_array_table($array) {
return "<table border=1>\n<tbody>\n" .
recursive_array_table_row($array) .
//implode("", array_map('recursive_array_table_row', array_keys($array), $array)) .
"</tbody>\n</table>\n";
}
function recursive_array_table_row($array) {
foreach($array as $key => $value) {
$content .= '<tr>';
if (is_array($value)) {
$content .= '<td colspan="1"><span style="color:#992222;">'.htmlspecialchars($key).'</span></td>';
$content .= '<td><span style="color:222299;">'.recursive_array_table($value).'</span></td>';
} else {
// Filter out some info...
//if (
//($key != "Error") &&
//($key != "SourceFile")
//) {
//if (!is_numeric($key)) {
$content .= '<td>'.htmlspecialchars($key).'</td>';
//}
$content .= '<td><span style="color:#229922;">'.$value.'</span></td>';
//}
}
$content .= '</tr>';
}
return $content;
}
function recursive_array_csv($array) {
//return is_array($array)
// ? "[" . implode(", ", array_map('array_csv', $array)) . "]"
// : htmlspecialchars($array);
}
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#submit_btn").click(function() {
post_data = {
'process_levels' : jQuery('select[name=process_levels]').val(),
'process_method' : jQuery('select[name=process_method]').val(),
'process_name' : jQuery('input[name=process_name]').val(),
'process_msg' : jQuery('textarea[name=process_message]').val()
};
jQuery.post('display_array_processor.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">Done! Here is the response:</div><div>'+response.text+'</div>';
}
jQuery("#contact_results").hide().html(output).slideDown();
}, 'json');
});
});
</script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="form-style" id="contact_form" style="max-width:650px;">
<div id="contact_results"></div>
<br />
<div id="contact_body">
<h3>Simple Bootstrap jQuery Ajax Form</h3>
Levels:
<select name="process_levels" id="process_levels" class="input-sm form-control" />
<option value="noheaders">No Headers</option>
<option value="headers">With Headers</option>
<option value="">None</option>
</select>
Method:
<select name="process_method" id="process_method" class="input-sm form-control" />
<option value="commas">Commas</option>
<option value="tables">Tables</option>
<option value="">None</option>
</select>
<input type="submit" id="submit_btn" value="Submit" />
</div>
</div>
</body>
</html>
Here is a way to generate a table where values will be represented as comma-separated as soon as the data is considered more suitable for that.
Concretely, data will be represented as comma-separated if it is a non-nested, sequential array, so without named keys.
Here it is:
// Two generic utility functions:
function is_nested($array) {
return is_array($array) && count($array) < count($array, COUNT_RECURSIVE);
}
function is_assoc($array) {
return is_array($array) && array_keys($array) !== range(0, count($array) - 1);
}
function array_table_row($key, $row) {
$content = array_table($row);
return "<tr>\n<th>$key</th>\n<td>$content</td>\n</tr>\n";
}
function array_table($array) {
if (is_nested($array) || is_assoc($array)) {
$content = implode("", array_map('array_table_row', array_keys($array), $array));
return "<table border=1>\n<tbody>\n$content</tbody>\n</table>\n";
}
// At this point $array is too simple for a table format:
$color = is_array($array) ? "922" : "292";
$content = htmlspecialchars(is_array($array) ? implode(", ", $array) : $array);
return "<span style='color:#$color'>$content</span>";
}
See in eval.in
Output for the "headers" sample data:
Previous answer:
function array_csv($array) {
return is_array($array)
? "[" . implode(", ", array_map('array_csv', $array)) . "]"
: htmlspecialchars($array);
}
function array_table_row($index, $row) {
return "<tr>\n <th colspan='2'>Row ". ($index+1) . "</th>\n</tr>\n" .
implode("", array_map(function ($key, $value) {
return "<tr>\n <td>" . htmlspecialchars($key) . "</td>\n" .
" <td><span style='color:#" . (is_array($value) ? "ccf" : "cfc") . ";'>" .
array_csv($value) . "</span></td>\n</tr>\n";
}, array_keys($row), $row));
}
function array_table($array) {
return "<table border=1>\n<tbody>\n" .
implode("", array_map('array_table_row', array_keys($array), $array)) .
"</tbody>\n</table>\n";
}
echo array_table($myArray);
See it run on eval.in.
This is the output for the sample data:
<table border=1>
<tbody>
<tr>
<th colspan='2'>Row 1</th>
</tr>
<tr>
<td>Size</td>
<td><span style='color:#cfc;'>914 kB</span></td>
</tr>
<tr>
<td>Date</td>
<td><span style='color:#cfc;'>2015:02:08 18:01:00-08:00</span></td>
</tr>
<tr>
<td>Attributes</td>
<td><span style='color:#cfc;'>Regular; (none)</span></td>
</tr>
<tr>
<td>Names</td>
<td><span style='color:#ccf;'>[Alex Smith, Mike Jones]</span></td>
</tr>
<tr>
<td>Keywords</td>
<td><span style='color:#ccf;'>[2015, Alex, Mike, snowboarding, [A snow, B cold, C fun]]</span></td>
</tr>
<tr>
<td>Software</td>
<td><span style='color:#cfc;'>Invisible Space-Monkey Monitoring System 01</span></td>
</tr>
<tr>
<td>Duration</td>
<td><span style='color:#cfc;'>4800</span></td>
</tr>
</tbody>
</table>
It was not clear from your question what you want to do when arrays are nested deeper, going beyond the level of the comma-separated values.
With the above code, the comma-separated lists are wrapped in brackets, so it is clear where sub-arrays start and end within such lists.
Note that you should escape some characters of your data (like less-than and ampersand characters) with a function like htmlspecialchars.
Related
I have notification table on my database where the value is using like json.
Here's my table
id | touserid | data
1 2 a:1:{i:0;s:10:"INV-000001";}
2 2 a:1:{i:0;s:10:"INV-000003";}
3 2 a:1:{i:0;s:15:"The Mej Hotel";}
4 1 a:5:{i:0;s:28:"Total Goalsi:1;s:7:"6250000";}
5 1 a:1:{i:0;s:10:"INV-000007";}
I want to use that value in html table, but I don't know how to convert the value to html table in codeigniter
Here's my view code
<table class="table table-dark">
<tbody>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Data</th>
<
</tr>
</thead>
<tbody>
<?php foreach($notifications as $notif){ ?>
<tr>
<td><?php echo $notif['id'] ?></td>
<td><?php echo $notif['data'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Here's controller code
$this->db->limit($this->misc_model->get_notifications_limit(), $offset);
$this->db->where('touserid', get_staff_user_id());
$this->db->order_by('date', 'desc');
$data['notifications'] = $this->db->get(db_prefix() . 'notifications')->result_array();
$this->load->view('admin/sales/sales', $data);
But I don't see the data value get into html table like I want, in table it's show the error message " not_goal_message_failedArray"
I'm trying to encode the json, but I still don't know how to pass the json encode in controller to view in codeigniter
Here's the json encode
$page = $this->input->post('page');
$offset = ($page * $this->misc_model->get_notifications_limit());
$this->db->limit($this->misc_model->get_notifications_limit(), $offset);
$this->db->where('touserid', get_staff_user_id());
$this->db->order_by('date', 'desc');
$notifications = $this->db->get(db_prefix() . 'notifications')->result_array();
$i = 0;
foreach ($notifications as $notification) {
if (($notification['fromcompany'] == null && $notification['fromuserid'] != 0) || ($notification['fromcompany'] == null && $notification['fromclientid'] != 0)) {
if ($notification['fromuserid'] != 0) {
$notifications[$i]['profile_image'] = '<a href="' . admin_url('staff/profile/' . $notification['fromuserid']) . '">' . staff_profile_image($notification['fromuserid'], [
'staff-profile-image-small',
'img-circle',
'pull-left',
]) . '</a>';
} else {
$notifications[$i]['profile_image'] = '<a href="' . admin_url('clients/client/' . $notification['fromclientid']) . '">
<img class="client-profile-image-small img-circle pull-left" src="' . contact_profile_image_url($notification['fromclientid']) . '"></a>';
}
} else {
$notifications[$i]['profile_image'] = '';
$notifications[$i]['full_name'] = '';
}
$data = '';
if (!empty($notification['data'])) {
$data = unserialize($notification['data']);
$x = 0;
foreach ($data as $dt) {
if (strpos($dt, '<lang>') !== false) {
$lang = get_string_between($dt, '<lang>', '</lang>');
$temp = _l($lang);
if (strpos($temp, 'project_status_') !== false) {
$status = get_project_status_by_id(strafter($temp, 'project_status_'));
$temp = $status['name'];
}
$dt[$x] = $temp;
}
$x++;
}
}
$notifications[$i]['description'] = _l($notification['description'], $dt);
$notifications[$i]['date'] = time_ago($notification['date']);
$notifications[$i]['full_date'] = $notification['date'];
$i++;
}
echo json_encode($notifications);
Do you know where's my error when tried convert the json value in the table to html table code ?
Thank you
Your data in your table is looking like a serialised array
You will not get the data via echo, should use
$this->load->view("notification_view", $notifications);
instead of
echo json_encode($notifications);
Hi guys i am trying to display the first td values as static so i have keep those values in one array and i try to increase the values and try to display but when i get it is displaying depending on foreach values if i have one record in foreach it is displaying one value and if i have 2 records it is displaying 2 values.
But i want to display all td value if i have values in foreach or not also.
Here is my code:
<tbody>
<?php
$arr = array(0=>'On Hold',1=>'Asset Incomplete',2=>'SME Discussion',3=>'a',4=>'b',5=>'c',6=>'d',7=>'e',8=>'f',9=>'g',10=>'h');
$i = 0;
foreach($getCourse as $report)
$status= $report->status;
{
?>
<tr>
<td><?php echo $arr[$i]; ?>
<?php $i++; ?></td>
<td><?php
if($status==1)
{
echo "On Hold";
}
elseif($status==2)
{
echo "Asset Incomplete";
}
elseif($status==3)
{
echo "Yet to Start";
}
elseif($status==4)
{
echo "SME Discussion";
}
elseif($status==5)
{
echo "Development";
}
elseif($status==6)
{
echo "PB Review";
}
elseif($status==7)
{
echo "PB Fixes";
}
elseif($status==8)
{
echo "PB2 Review";
}
elseif($status==9)
{
echo "PB2 Fixes";
}
elseif($status==10)
{
echo "Alpha Development";
}
elseif($status==11)
{
echo "Alpha Review";
}
elseif($status==12)
{
echo "Alpha Fixes";
}
elseif($status==13)
{
echo "Beta Review";
}
elseif($status==14)
{
echo "Beta Fixes";
}
elseif($status==15)
{
echo "Gamma";
}
?></td>
<td><?php echo $report->coursename; ?></td>
<td><?php echo $report->statuscount;?></td>
<td></td>
</tr>
<?php
}
?>
</tbody>
Here is my controller:
public function index()
{
if ($this->session->userdata('is_logged')) {
$data['getCourse']=$this->Report_model->getTopicReports();
$this->load->view('template/header');
$this->load->view('reports/report',$data);
$this->load->view('template/footer');
}
else {
redirect("Login");
}
}
Here is my model:
public function getTopicReports()
{
$this->db->select('count(t.status) as statuscount,t.topicName as topicname,c.coursename,t.status')
->from('topics t')
->join('course c', 't.courseId = c.id')
->where('t.courseid',1)
->where('t.status',5);
$query = $this->db->get();
return $query->result();
}
This is how i want to display here is my referrence image:
Can anyone help me how to do that thanks in advance.
FINAL UPDATED & WORKING VERSION
For me this was tricky. This turned out to be what I felt to be a awkward indexing issue.
The problem is that your data is not optimized very well to accommodate the task you are asking for. You have to make odd comparisons as you traverse the table. I was able to get it accomplished.
I would actually be very interested in seeing a more refined approach. But until that happens this code will dynamically generate a table that matches the output of the sample pictures that you posted in your question.
I have tested this code with some sample data that matches the array structure that you posted in your comments.
Here is the code:
//Create an array with your status values.
$rowName = array(
'On Hold',
'Asset Incomplete',
'Yet to Start',
'SME Discussion',
'Development',
'PB Review',
'PB Fixes',
'PB2 Review',
'PB2 Fixes',
'Alpha Development',
'Alpha Review',
'Alpha Fixes',
'Beta Review',
'Beta Fixes',
'Gamma'
);
//Generate a list of class names and get rid of any duplicates.
foreach($getCourse as $report){
$courseNames[] = $report->coursename;
}
$courseNames = array_unique($courseNames);
//Create the header.
echo
'<table>
<thead>
<tr>
<th>#</th>';
foreach($courseNames as $course){
echo '<th>' . $course . '</td>';
}
echo
'<th>Total</th>
</tr>
</thead>
<tbody>';
//Iterate across the array(list) of status values.
for($i = 0; $i < count($rowName); $i++){
echo
'<tr>';
echo '<td>' . $rowName[$i] . '</td>';
//Iterate through all combinations of class names and status values.
for($j = 0; $j < count($courseNames); $j++){
//Set flags and intial values.
$found = FALSE;
$total = 0;
$value = NULL;
for($k = 0; $k < count($getCourse); $k++){
//***Note - The ""$getCourse[$k]->status - 1" is because the status values in your data do not appear
//to start with an index of 0. Had to adjust for that.
//Sum up all the values for matching status values.
if(($getCourse[$k]->status - 1) == $i){
$total += $getCourse[$k]->statuscount;
}
//Here we are checking that status row and the status value match and that the class names match.
//If they do we set some values and generate a table cell value.
if(($getCourse[$k]->status - 1) == $i && $courseNames[$j] == $getCourse[$k]->coursename){
//Set flags and values for later.
$found = TRUE;
$value = $k;
}
}
//Use flags and values to generate your data onto the table.
if($found){
echo '<td>' . $getCourse[$value]->statuscount . '</td>';
}else{
echo '<td>' . '0' . '</td>';
}
}
echo '<td>' . $total . '</td>';
echo
'</tr>';
}
echo '</tbody>
</table>';
Try this. I am storing course status in $used_status then displaying the remaining status which are not displayed in foreach.
$arr = array ( '1' =>'On Hold', '2' => 'Asset Incomplete', '3' => 'SME Discussion', '4' => 'a', '5' => 'b', '6' => 'c', '7' =>'d', '8' => 'e', '9' => 'f', '10' => 'g', '11' => 'h' );
$used_status = array();
foreach($getCourse as $report) { ?>
<tr>
<td>
<?php $course_status = isset($arr[$report->status]) ? $arr[$report->status] : "-";
echo $course_status;
$used_status[] = $course_status; ?>
</td>
<td>
<?php echo $report->coursename; ?>
</td>
<td>
<?php echo $report->statuscount; ?>
</td>
</tr>
<?php }
foreach($arr as $status) {
if(!in_array($status, $used_status)) { ?>
<tr>
<td>
<?php echo $status; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
</tr>
<?php }
} ?>
I am having two set off arrays, first array is holding data about colors, second about dimensions.
$colors= array(
"27" => "RAL 9002",
"255" => "RAL 9006",
"341" => "RAL 8019",
"286" => "RAL 7016",
"141" => "RAL 3009",
"171" => "RAL 6028",
"121" => "RAL 8004",
"221" => "RAL 5010",
"101" => "RAL 3000",
"273" => "RAL 9007",);
$dimensions = array
(
array(0.3,1245),
array(0.35,1245),
array(0.40,1100),
array(0.45,1245),
array(0.50,1245),
array(0.60,1245),
array(0.70,1245),
);
Values above are used for queries. I wanted to make an array which will hold data, and later in comparison will print data. Query can return result NULL
foreach($colors as $key => $value)
{
//print "Boja $key . <br>";
foreach($dimensions as $data )
{
//print "Debljina $data[0], Sirina $data[1] Boja $key <br>";
$sql = "SELECT Debljina, Sirina, sum(Kolicina) as suma
FROM jos_ib_repromaterijali WHERE Debljina = '$data[0]' AND Sirina = '$data[1]' AND Boja = '$key'";
$q = $conn -> query($sql);
$vrijednosti = array();
while($r=$q->fetch()) {
$debljina = $r['Debljina'];
$sirina = $r['Sirina'];
$kolicina = $r['suma'];
$vrijednosti[] = $debljina . $sirina . $kod . $kolicina;
}
}
}
Once I get results, I create html table
<div class="col-lg-6">
<table class="table table-bordered">
<thead>
<tr>
<th><?php echo "Dimenzije"; ?> </th>
<?php foreach($colors as $boja) { ?>
<th><?php echo $boja; ?> </th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php foreach($dimensions as $dim) {
?>
<tr>
<td><?php echo $dim[0] . ' X ' . $dim[1]; ?> </td>
<td><?php
if (isset($vrijednosti[$dim[0] . $dim[1]])) {
echo "asdas";
}
else {
echo "error";
}
?> </td>
</tr>
<?php }
?>
</tbody>
</table>
Table print headers and dimensions as it should, I am having trouble in matching rows with column. If someone give me an advice it would be appreciated.
Query can give result NULL; if that is result It should print 0 below color for specific row.
I wrote some code to display a html table with PHP.
It reads data from a file and checks whether the value is true or false.
The problem is the ugly appearance of the table at the end of the function:
True False
blue
Red
Red
blue
I would like to display the table like this:
True False
blue Red
blue Red
Also it displays the outcome before the function is finished c.q flush();
Here is the code:
?>
<table>
<tr>
<th>True</th>
<th>False</th>
</tr>
<?php foreach ($trimmed_array as $value) { ?>
<tr>
<?php if (check($value) == 0) { ?>
<td><?php print $value ?></td>
<td> </td>
<?php
} else { ?>
<td> </td>
<td><?php print $value ?></td>
<?php
}
sleep(1);
ob_flush();
flush();
} ?>
</table>
I realize this code outputs the table like the first example but I can`t seem to figure out how to change it to fit the second example?
Your code creates one table row per item in the array, so there will always be one blank column per row.
In the 'table' that you would like to display, the items in each row aren't related to each other.
So really you're creating 2 lists here, not a table as such.
I'd do something like this
<?php
$all_values = array('true' => array(), 'false' = array());
foreach($trimmed_array as $value){
if (check($value) == 0){
$all_values['true'][] = $value;
}else{
$all_values['false'][] = $value;
}
}
foreach($all_values as $name => $values){
?>
<ul class="<?php print $name;?>">
<?php
foreach($values as $value){
?>
<li><?php print $value; ?></li>
<?php
}
?>
</ul>
<?php
}
?>
You can then arrange your lists side by side with CSS
$true = array();
$false = array();
foreach ($trimmed_array as $value) {
if (check($value) == 0) {
$true[] = $value;
} else {
$false[] = $value;
}
}
for ($i = 0; $i < max(count($true), count($false)); $i++) {
echo '<tr>
<td>' . (isset($true[$i]) ? $true[$i] : '') . '</td>
<td>' . (isset($false[$i]) ? $false[$i] : '') . '</td>
</tr>';
}
I have a chart and a text file that is taking in some data. I would like to organize the data I have by putting the user with the highest score on the top of the table and coloring everything in their row blue. Any idea how I could do this?
file one:
<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<title>High Score</title>
</head>
<body>
form action="data.php" method="POST">
<table border="1">
<tr><td>Player Name</td><td><input type="text" name="name"</td></tr>
<tr><td>Score</td><td><input type="text" name="score"</td></tr>
<tr><td colspan="2" align="center"><input type="submit"></td></tr>
</table>
</form>
</body>
</html>
Data.php:
<?php
$name = $_POST['name'];
$score = $_POST['score'];
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
# $fp = fopen("$DOC_ROOT/../phpdata/highscore.txt","ab");
if(!$fp) {
echo 'Error: Cannot open file.';
exit;
}
fwrite($fp, $name."|".$score."\n");
?>
<?php
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
$players = file("$DOC_ROOT/../phpdata/highscore.txt");
echo "<table border='2'>";
echo "<tr> <td>Name</td> <td>Score</td> </tr>";
for($i = 0; $i < sizeof($players); $i++) {
list($name,$score) = explode('|', $players[$i]);
echo '<tr><td>'.$name.'</td><td>'.$score.'</td></tr>';
}
echo '</table>';
?>
Format all players/scores into arrays like array('name' => 'Bob', 'score' => 42):
foreach ($players as &$player) {
list($name, $score) = explode('|', $player);
$player = compact('name', 'score');
}
unset($player);
Sort the array by score (PHP 5.3 syntax):
usort($players, function ($a, $b) { return $b['score'] - $a['score']; });
Output the results, setting a class on the first row:
$first = true;
foreach ($players as $player) {
$class = $first ? ' class="highlight"' : null;
$first = false;
printf('<tr%s><td>%s</td><td>%s</td></tr>', $class, htmlspecialchars($player['name']), htmlspecialchars($player['score']));
}
Now highlight that class using CSS (or do it directly in the HTML, or whatever else you want to do).