Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
When I learned to program, we only had Arrays, no Objects.
Now I am trying to get into the habit of using Objects, rather than always shoe-horning arrays.
Today I am trying to store tabular Data in an object.
[b]
$table =
1 a b c
2 x y z
3 e d f
[/b]
In my example I am storing the filename, file size, and creation dates for all the files in a folder, but it could be any data matrix.
Sounds good....until I tried it.
I can't figure out how to assign an unspecified number of properties in a class, without falling back on arrays.
My first property ends up being an array, and I essentially end up with one array representing to table rows, holding smaller arrays containing the fields.
I feel like I am 'missing something'. There probably is a very obvious/clever way to do this, but I need someone to point me in the right direction.
Here is what I wrote this morning.
It works. I have a method called [b]sort[/b] which allows me to sort my 'table' based on any field.
It just feels like a hack. Please let me know if there is a better way to create an Object which stores a table's worth of data.Code: Select all
<?php
class table
{
var $rows = array();
var $count = 0;
function add($row)
{
$this->rows[$this->count] = $row;
$this->count++;
}
var $sort_field;
private function sort_by_field($a,$b)
{
if ($a[$this->sort_field] == $b[$this->sort_field])
return 0;
if ($a[$this->sort_field] > $b[$this->sort_field])
return 1;
else
return -1;
}
function sort($field)
{
$this->sort_field=$field;
usort($this->rows,array('table','sort_by_field'));
}
}
$myfolder= new table();
$directory=$_SERVER['DOCUMENT_ROOT']."/pdf";
$dp = opendir($directory);
while($file = readdir($dp))
{
if($file != '.' && $file != '..')
{
$file_object= array();
$file_object[]=$file;
$file_object[]=filesize("$directory/$file");
$file_object[]=filemtime("$directory/$file");
$myfolder->add($file_object);
}
}
closedir($dp);
$myfolder->sort(1);
foreach($myfolder->rows as $row)
{
foreach($row as $field)
echo $field.'....';
echo '<br>';
}
?>Weirdan | Please use
Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]