Page 1 of 1

Array n00b

Posted: Sun Nov 18, 2007 3:19 pm
by wildwobby
Alright, its been a while since I've screwed with php... so I wanted to dive back in thought I'd make a little txt powered thingy...

Class:

Code: Select all

<?php
class App{
	public function __construct(){
		include 'home.php';
	}
}
class Posts{
	var $file = 'posts.txt';
	public function __construct(){
	}
	
	public function makePost($sub,$date,$author,$content){
		if(is_writable($this->file)){
			if (!$handle = fopen($this->file, 'a')){
				echo "Cannot open file ($this->file)";
				exit;
			}
			$post = $sub.':'.$date.':'.$author.':'.$content."\n";
			if (fwrite($handle, $post) === FALSE){
				echo "Cannot write to file ($this->file)";
				exit;
			}
			fclose($handle);
			return true;
		} else {
			echo "File ($this->file) was not writable";
			return false;
		}
	}
	public function getPosts($num){
		$handle = fopen($this->file, 'r');
		$posts = array();
		if($handle){
			for($i = 0; ($i <= ($num - 1)) && !feof($handle); $i++){
				if($ipost = fgets($handle)){
					$info = explode(':',$ipost);
					$posts[$i]['sub'] = $info[0];
					$posts[$i]['date'] = $info[1];
					$posts[$i]['author'] = $info[2];
					$posts[$i]['content'] = $info[3];
				}
			}
		}
		return $posts;
	}
}
?>
Code that calls it:

Code: Select all

<?php
include 'classes.php';
$post = new Posts();
$posts = $post->getPosts(3);
echo "<table>";
for($i = 0; $i <= (count($posts)-1); $i++){
	echo "<tr>
			<td>$posts[$i]['sub']</td>
			<td>$posts[$i]['date']</td>
			<td>$posts[$i]['author']</td>
			<td>$posts[$i]['content']</td>
		</tr>";
}
echo "</table>";
echo "done!";
?>
The thing is, it outputs like this:
http://67.175.40.166/~wildwobby/identifiers/read.php

What did i mess up? php 5.2.5

Posted: Sun Nov 18, 2007 3:33 pm
by John Cartwright

Code: Select all

for($i = 0; $i <= (count($posts)-1); $i++){
   echo '<tr>
         <td>'. $posts[$i]['sub'] .'</td>
         <td>'. $posts[$i]['date'] .'</td>
         <td>'. $posts[$i]['author'] .'</td>
         <td>'. $posts[$i]['content'] .'</td>
      </tr>';
}
You need to break out of quotes to parse arrays or wrap the variable in { }

Posted: Sun Nov 18, 2007 3:39 pm
by wildwobby
Yay, it works!

Thanks a lot!