2 Replies - 2398 Views - Last Post: 25 April 2014 - 05:58 AM Rate Topic: -----

#1 typhlosion   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 121
  • Joined: 09-December 13

creating a multidimensional array with a recursive function

Posted 25 April 2014 - 02:41 AM

Hello to all.

The title says it all, trying to create multi D array with good ol recursive function


As far as I got being the noob I am :dontgetit:/>
class Categories{
	
	public $tree;
	
	function __construct(){
		return false;
	}
        
        //tree seemed like a suitable name  :rolleyes2:/>/> 
	public function tree($id, $depth = 0){
		$sql = "SELECT * FROM category WHERE id=$id";
		$query = Database::get()->query($sql);
		$depth++;
		if($query->rowCount() > 0){
			foreach($query as $row){
				//create the array
                                $this->array .= ??????;
				$this->tree($row['id'], $depth);
			}
		}
		return $this->array;
	}
}



Also once it's in an array how would I return this array to be used to structure some HTML I am making this function as I will have things such as drop down menus and <select> menus that will all be using the same data so they can share :tup:/>

This post has been edited by typhlosion: 25 April 2014 - 02:41 AM


Is This A Good Question/Topic? 0
  • +

Replies To: creating a multidimensional array with a recursive function

#2 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4278
  • View blog
  • Posts: 13,573
  • Joined: 08-June 10

Re: creating a multidimensional array with a recursive function

Posted 25 April 2014 - 03:51 AM

to make an n-D array you must not use $this->array. just make a local array and return that.

$tree = array();
foreach($query as $row){
  $tree[] = $this->tree($row['id'], $depth);
}
return $tree;



some important notes, though:
- the row count condition is pointless. if the result set is empty, the loop won’t run.
- your SQL is ... doubtful (at best), you’d just get the same value nested.
- you’re missing the abort condition.

you may also want to have a look at the Composite Pattern.
Was This Post Helpful? 0
  • +
  • -

#3 CTphpnwb   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3837
  • View blog
  • Posts: 13,998
  • Joined: 08-August 08

Re: creating a multidimensional array with a recursive function

Posted 25 April 2014 - 05:58 AM

Please explain why you're not using prepared statements.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1