PHP - Parent\child\child Array
Hi I am trying to create a hierarchy array from our mysql database. What i have so far is: //instantiate DB & connect $database = new Database(); $db = $database->connect(); //instantiate question object $question = new Question($db); //query $results = $question->read(); //check for data if ($results) { $question_arr['questions'] = array(); $child_arr = array(); while ($row = $results->fetch(PDO::FETCH_ASSOC)) { array_push($question_arr['questions'], $row); $question_arr['questions'][] = buildTree($row); } print_r($question_arr['questions']); } else { echo json_encode(array('message'=>'nothing here!.')); } function buildTree($child) { $branch = array(); foreach ($child as $row) { $childresults = $question->read_children($row['parentid']); while ($childrow =$childresults->fetch(PDO::FETCH_ASSOC)) { $children = buildTree($childrow); if ($children) { $row['children'] = $children; } $branch[] = $childrow; } } //} return $branch; } in my Questions.php file: <?php class Question{ private $conn; public $id; public $childid; public $parentid; public $question; public $pageid; public $numclicks; public $typeid; public $date_created; // Constructor with DB public function __construct($db) { $this->conn = $db; } public function read() { //create query(sql statement) $query = 'SELECT id as parentid, question, pageid, typeid,numclicks,date_created from ct_questions'; // Prepare statement $stmt =$this->conn->prepare($query); // Execute query $stmt->execute(); return $stmt; } public function read_children($parentid) { //This is from a View I created in Mysql $query = 'SELECT parent_question, parentid, parent_pageid, child_question, childid, child_pageid from ct_vquestion_parent_child_lookup where parentid='.$parentid.''; // Prepare statement $stmt = $this->conn->prepare($query); // Execute query $stmt->execute(); return $stmt; } }
the current errors i am getting a <br /> <b>Notice</b>: Undefined variable: question in <b>C:\htdocs\api\questions\read.php</b> on line <b>41</b><br /> <br /> <b>Fatal error</b>: Uncaught Error: Call to a member function read_children() on null in C:\htdocs\api\questions\read.php:41 Stack trace: #0 C:\htdocs\api\questions\read.php(28): buildTree(Array) #1 {main} thrown in <b>C:\htdocs\api\questions\read.php</b> on line <b>41</b><br /> Similar TutorialsI'm pulling a list of topics from my DB and they are structured hierarchally using the typical id | parent_id scheme The array I end up with from the DB is one large one with keys representing the unique id of each data result...The problem is getting past the 2d scope of the array. I know this will require a recursive function and I've been at it for hours but can't seem to wrap my hurting head around it! How do I get my orignal array in this form: Array ( [0] => Array ( [1] => top parent [2] => top parent [3] => top parent [9] => top parent ) [2] => Array ( [4] => #1 child of 2 [5] => #2 child of 2 ) [3] => Array ( [6] => #1 child of 3 ) [4] => Array ( [7] => #1 child(subsub) of 4 [8] => #2 child(subsub) of 4 ) ) To look something more like this? : Array ( [1] => top parent [2] => Array ( [4] => Array ( [7] => #1 child(subsub) of 4 [8] => #2 child(subsub) of 4 ) [5] => #2 child of 2 ) [3] => Array ( [6] => #1 child of 3 ) [9] => top parent ) notice how the 2nd array has all the proper dimensions according the the DB hierarchy. Thank you ps. or maybe I should work from a different array to start from...I'm open to suggestions I have one table but i try to make like the result not finished.
Hmm.. can you see my table :
FireShot Screen Capture #003 - 'localhost _ 127_0_0_1 _ pmis_dbase _ rekening_kegiatan I phpMyAdmin 4_0_4_1' - localhost_phpmyadmin_index_php_db=pmis_dbase&table=rekening_kegiatan&target=sql_php&token=93960ef7b5.png 803.36KB
0 downloads
I want to declare sum for parent kd_rekening in same row for "Anggaran" => jns_anggaran =1 and "Perubahan" => jns_anggaran = 2. And child ust load field nilai. Untitled.jpg 34.7KB 0 downloads Thanks before Hello. i have some code that works with out using parent and child but i dont think im doing it in the correct oop way. would someone maybe please just have a little look for me please. by the way.. i know im not ment to use global but thats how i was shown to do that on my tutorial videos.. i'll address that in another post so. in this example i have this pages class Code: [Select] <?PHP require_once(LIB_PATH.DS.'database.php'); class Pages { protected static $table_name="pages"; protected static $db_fields = array( 'id', 'pageName', 'contTemp_id', 'contElements_id', 'title', 'sub_title', 'description', 'about', 'image', 'created', 'dateMod', 'timeMod'); public $id; public $pageName; public $contTemp_id; public $contElements_id; public $title; public $sub_title; public $description; public $about; public $image; public $created; public $dateMod; public $timeMod; // "new" is a reserved word so we use "make"(or "build") public static function make( $id="", $pageName="", $contTemp_id="", $contElements_id="", $title="", $sub_title="", $description="", $about="", $image="", $created="", $dateMod="", $timeMod="") { if(!empty($title)) { $kw = new NavL3(); $kw->id = (int)$id; $kw->pageName = $pageName; $kw->contTemp_id = (int)$contTemp_id; $kw->contElements_id = (int)$contElements_id; $kw->title = $title; $kw->sub_title = $sub_title; $kw->description = $description; $kw->about = $about; $kw->image = $image; $kw->created = $created; $kw->dateMod = $dateMod; $kw->timeMod = $timeMod; return $kw; }else{ return false; } } //end function make public static function find_by_pageName($id){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id='".$database->escape_value($id)."'"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } public static function find_by_pageID($pageID=0){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($pageID)." LIMIT 1"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } // Common Database Methods public static function find_all(){ global $database; $sql = "SELECT * FROM ".self::$table_name.""; return self::find_by_sql($sql); } public static function find_by_id($id=0){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($id)." LIMIT 1"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } public static function find_by_sql($sql){ global $database; $results_set = $database->query($sql); $object_array = array(); while($row = $database->fetch_array($results_set)){ $object_array[] = self::instantiate($row); } return $object_array; } public static function count_all(){ global $database; $sql = "SELECT COUNT(*) FROM ".self::$table_name; $results_set = $database->query($sql); $row = $database->fetch_array($results_set); return array_shift($row); } public static function instantiate($result){ $object = new self; foreach($result as $attribute => $value){ if($object->has_attribute($attribute)){ $object->$attribute = $value; } } return $object; } private function has_attribute($attribute){ $object_vars = $this->attributes(); return array_key_exists($attribute, $object_vars); } protected function attributes(){ $attributes = array(); foreach(self::$db_fields as $field){ if(property_exists($this, $field)){ $attributes[$field] = $this->$field; } } return $attributes; } protected function sanitized_attributes(){ global $database; $clean_attributes = array(); foreach($this->attributes() as $key => $value){ $clean_attributes[$key] = $database->escape_value($value); } return $clean_attributes; } public function save(){ return !empty($this->id) ? $this->update() : $this->create(); } public function create(){ global $database; $attributes = $this->sanitized_attributes(); $sql = "INSERT INTO ".self::$table_name." ("; $sql .= join(", ", array_keys($attributes)); $sql .= ") VALUES ('"; $sql .= join("', '", array_values($attributes)); $sql .= "')"; if($database->query($sql)){ $this->id = $database->insert_id(); return true; }else{ return false; } } public function update(){ global $database; $attributes = $this->sanitized_attributes(); $attribute_pairs = array(); foreach($attributes as $key => $value){ $attribute_pairs[] = "{$key}='{$value}'"; } $sql = "UPDATE ".self::$table_name." SET "; $sql .= join(", ", $attribute_pairs); $sql .= " WHERE id=".$database->escape_value($this->id); $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } public function delete(){ global $database; $sql = "DELETE FROM ".self::$table_name." "; $sql .= "WHERE id=".$database->escape_value($this->id); $sql .= " LIMIT 1"; $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } } //end class blogs ?> and i have this conttemp class Code: [Select] <?PHP require_once(LIB_PATH.DS.'database.php'); class Conttemps { protected static $table_name="contTemps"; protected static $db_fields = array( 'id', 'name', 'created', 'dateMod', 'timeMod'); public $id; public $name; public $created; public $dateMod; public $timeMod; // "new" is a reserved word so we use "make"(or "build") public static function make( $id, $name="", $created="", $dateMod="", $timeMod="") { if(!empty($name)) { $kw = new Templates(); $kw->id = (int)$id; $kw->name = $name; $kw->created = $created; $kw->dateMod = $dateMod; $kw->timeMod = $timeMod; return $kw; }else{ return false; } } //end function make public function find_contTemp($pageID){ $page = Pages::find_by_pageID($pageID); $pageCID = $page->contTemp_id; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$pageCID.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } // Common Database Methods public static function find_all(){ global $database; $sql = "SELECT * FROM ".self::$table_name.""; return self::find_by_sql($sql); } public static function find_by_id($id=0){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($id)." LIMIT 1"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } public static function find_by_sql($sql){ global $database; $results_set = $database->query($sql); $object_array = array(); while($row = $database->fetch_array($results_set)){ $object_array[] = self::instantiate($row); } return $object_array; } public static function count_all(){ global $database; $sql = "SELECT COUNT(*) FROM ".self::$table_name; $results_set = $database->query($sql); $row = $database->fetch_array($results_set); return array_shift($row); } public static function instantiate($result){ $object = new self; foreach($result as $attribute => $value){ if($object->has_attribute($attribute)){ $object->$attribute = $value; } } return $object; } private function has_attribute($attribute){ $object_vars = $this->attributes(); return array_key_exists($attribute, $object_vars); } protected function attributes(){ $attributes = array(); foreach(self::$db_fields as $field){ if(property_exists($this, $field)){ $attributes[$field] = $this->$field; } } return $attributes; } protected function sanitized_attributes(){ global $database; $clean_attributes = array(); foreach($this->attributes() as $key => $value){ $clean_attributes[$key] = $database->escape_value($value); } return $clean_attributes; } public function save(){ return !empty($this->id) ? $this->update() : $this->create(); } public function create(){ global $database; $attributes = $this->sanitized_attributes(); $sql = "INSERT INTO ".self::$table_name." ("; $sql .= join(", ", array_keys($attributes)); $sql .= ") VALUES ('"; $sql .= join("', '", array_values($attributes)); $sql .= "')"; if($database->query($sql)){ $this->id = $database->insert_id(); return true; }else{ return false; } } public function update(){ global $database; $attributes = $this->sanitized_attributes(); $attribute_pairs = array(); foreach($attributes as $key => $value){ $attribute_pairs[] = "{$key}='{$value}'"; } $sql = "UPDATE ".self::$table_name." SET "; $sql .= join(", ", $attribute_pairs); $sql .= " WHERE id=".$database->escape_value($this->id); $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } public function delete(){ global $database; $sql = "DELETE FROM ".self::$table_name." "; $sql .= "WHERE id=".$database->escape_value($this->id); $sql .= " LIMIT 1"; $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } } //end class blogs ?> the bit im interested in is this function in the Conttemp class Code: [Select] public function find_contTemp($pageID){ $page = Pages::find_by_pageID($pageID); $pageCID = $page->contTemp_id; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$pageCID.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } it call a function in from the Pages class. i could take the function from here and put it in the Pages class i guess but i was wondering about Exends. should i do class Conttemps extends Pages { and use something like Code: [Select] public function find_contTemp($pageID){ $pageCID= Pages::contTemp_id; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$pageCID.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } i guess that wont work because its not getting the $pageID but anyway.. any thoughts ???? thanks rick Code: [Select] Main Object ( [Visitor] = Visitor Object ( [user_info] => Array ( [username] = user [user_id] = 1 ) ) [Room] = Room Object ( [info] = Array( [id] = 1 [name] = Lobby ) [messages] = Messages Object ( [messages] = Array ( [0] = Array() ) ) ) ) Is there a way to get the visitor info within the Messages Object? I'm building it such as $Main = new Main; $Main->Visitor = new Visitor; $Main->Room = new Room; $Main->Room->Messages = new Messages; so they're not static I know that I can pass the $this var through each but that duplicates the class each time and I'm 99% sure that's bad. Ok, here is the whole code for the downline, but the problem is that it doesn't show members below that one I mean if b follows a, and c follows b and I opened the page of A, it will only show A's info, and not bring B and C in the downline Code: [Select] <?php if($_REQUEST["i"]){ GenerateTree($_REQUEST["i"]); } else{ GenerateTree($_GET['id']); } function GenerateTree($memberid){ $l1="<img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' />";$l2="<img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' />"; $query = "SELECT * FROM users where recruiteris='".$memberid."' order by type"; //echo $query; $result = mysql_query($query); //var_dump($result); while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { if($row["type"]=="Company"){$l1=getDownline($row["id"]);} if($row["type"]=="client"){$l2=getDownline($row["id"]);} } mysql_free_result($result); echo "<table border='0' class='mainTable' cellspacing='0' cellpadding='3' style='width:100%'>\n"; echo "<tr><td colspan='3' style='text-align:center;'>Login ID: ".$memberid.getInfo($memberid)."<br />"."</td></tr>"; echo "<tr><td colspan='3'>".getDownline($memberid)."</td></tr>"; echo "<tr><td style='width:33%;'>".$l1."</td><td style='width:33%;'>".$l2."</td>"; echo "</table>\n"; } function getDownline($memberid){ $query = "SELECT * FROM users where recruiteris='".$memberid."' order by type"; //echo $query; $result = mysql_query($query); //var_dump($result); $final = "<table border='0' style='width:100%;' class='internalTable' cellspacing='0' cellpadding='2'>\n"; $final .= "<tr>"; $nothing=true; $x=0; $pre; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { $x++; $_SESSION['s']=0; if($row["type"]=="Company" && $x==1){$final .= "<td style='width:33%; background-color:#FFFFEC;' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";} if($row["type"]=="client" && $x==2){$final .= "<td style='width:33%; background-color:#E1F0FF;' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";} if($row["type"]=="client" && $x==1){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td><td style='width:33%; background-color:#E1F0FF' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";} $pre = $row["type"]; $nothing=false; } if($nothing){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td><td style='width:34%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td>"; } if($x==1 && $pre=="Company"){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td>";} mysql_free_result($result); $final .= "</tr>"; $final .= "</table>\n"; return $final; } function getToolTip($id){ $query = "SELECT * FROM users where id ='".$id."'"; $result = mysql_query($query); $res; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { $res = "fade=[off] cssheader=[toolHeader] cssbody=[toolBody] header=[Detail For ID () - ".$id."] body=[".$row["m_name"]."<br />Address:<br />".$row["address"]."]"; } mysql_free_result($result); return $res; } function getInfo($id){ $query = "SELECT * FROM users where id='".$id."'"; $result = mysql_query($query); $res; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { $res = "<br />Name: ".$row["fname"]."<br />National ID: ".$row["nid"]."<br />"; } mysql_free_result($result); return $res; } function getCount($id){ $query = "SELECT * FROM users where recruiteris='".$id."'"; $result = mysql_query($query); $count = mysql_num_rows($result); $_SESSION['s'] = $_SESSION['s']+$count; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { getCount($row["id"]); } mysql_free_result($result); //echo $count."<br />"; return ""; } // Closing connection mysql_close($link); ?> I have a user class that is very dependent on the database class, which is why the user class extends the database. I tried creating a protected method in the parent class called getDBCObject, which returned the database object/variable/handle that I want the user to have access to. I tried the method below, but it doesn't work: <?php /* * @DATABASE * ~~~~~~~~~~~~ * @FILE DESCRIPTION: Handles all database related processes * @LAST MODIFIED: April 4, 2012 */ class database { protected $dbc; function __construct($db_host, $db_name, $db_user, $db_password) { try { $this->dbc = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password); } catch(PDOException $e) { echo '<b>An error occured while trying to create a database connection: </b>'. $e->getMessage(); } } /* * @METHOD getDBCObject * @DESC Gives the $dbc object/variable to its child classes */ protected function getDBCObject() { return $this->dbc; } } ?> My user class: <?php /* * @DATABASE * ~~~~~~~~~~~~ * @FILE DESCRIPTION: User related proccess * @LAST MODIFIED: April 5, 2012 */ class user extends database { protected $dbc; public function __construct() { if(parent::getDBCObject() == null) { echo '<br/>A database class/connection is required before creating the user class.'; } } public function isLoggedIn() { if($_COOKIE['user']) { //soon to come } else { return false; } } } ?> Any feedback on how I can let the user class use the $dbc variable in the database class? I have a major problem; I have two tables - Category and Product The catID is the primary key for Category and acts as the foreign key for Product. I have some example data below; CATEGORY catID: 3 cat: Pink PRODUCT prodID: 1 product: Fuchsia catID: 3 prodID: 2 product: Dark Pink catID: 3 what I want is the page to display the data like this? Header: Pink Content: Fuchsia Dark Pink Below is the code thus far; Code: [Select] <?php error_reporting(E_ALL ^ E_NOTICE); ini_set("display_errors", 1); require ('includes/config.inc.php'); include ('./includes/header.html'); require (MYSQL); include ('./includes/main.html'); if($id = isset($_GET['catID'])) { $q = ('SELECT `category`.`catID` , `category`.`cat` , `product`.`product` FROM `product` LEFT JOIN `hairext`.`category` ON `product`.`catID` = `category`.`catID` WHERE `product`.`catID`="'.$_GET['catID'].'"'); $r = mysqli_query($dbc, $q); echo '<div id="right">'; $num = mysqli_num_rows($r); for ($j = 0 ; $j < $num ; ++$j) { $row = mysqli_fetch_row($r); echo '<h1>' . $row[1] . '</h1>'; } while($row = mysqli_fetch_array($r)) { echo '<p>'; echo $row[2]; echo "<br />"; echo '</p>'; } echo '</div>'; } include ('./includes/footer.html'); ?> At the moment, this is not doing what I want, I apologise if this is very long winded, but how do I solve this problem please? Why won't my unset remove the array from the parent $data[0] array? Code: [Select] foreach ($data[0] as $k => $r) { if (($r['feedid'] !== $user_info['uid']) && ($r['action_id'] == 'newuser')) { unset($data[0][$k]); } } Hi, I've a two classes A,B. A is a parent class and B is a child class. B is extends from A. I made an object of class A. Now i want to access function of class B from this object instance. e.g Code: [Select] class A { function myfunctiona() { ....... ....... } } class B extends A { function chlidfunction() { return "hyne"; } } $sani = new A(); //here i want to access echo $sani->b->childfunction(); please guide how can called child class function from parent object instance? Thanks class Database { // actual database interaction // also uses mysql_real_escape etc. } class Users extends Database { function checkIfUsernameExists() { } } class addUser extends Users { // perform all add user stuff } class searchUser extends Users { // all search user stuff } So, to add a new user, I would instantiate, then perform various queries to the addUser class, probably also using the checkIfUsernameExists method in the Users class. Finally, Database would add the record. Question: what do I instantiate? Do I instantiate just the addUser one, or first the Database class? I know how to do it, but what about instantiation, using parent:: self:: etc. etc. (how do I link these clasess together is what I think I mean). I have these two classes: Code: [Select] <?php class A { private $id; public function __construct() { $this->id = '11111'; } public function getProperty($prop) { return $this->$prop; } }?> Code: [Select] <?php class B extends A { private $message = "Nope, can't see it"; public function __construct() { parent::__construct(); $this->message = "Yep, I can see it"; } }?> I tried this, but it just outputs the id (the first call) Code: [Select] $class = new B; echo $class->getProperty('id'); echo $class->getProperty('message'); Why is that? I thought I could use a parent method on a child property.. *EDIT* Using a public or protected visibility on the message property gets me the output I expect...how come? This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=356195.0 Mmm i'm not sure if i'm approaching this correctly. Anyways, I wanted to create a multi-level thread, Where the child thread would be after the parent thread. Something like this: Hello World - Hello World - Hi! - What's up? - Hi Bob! Goodbye World - ....This guy got issues - Dude! You should watch Despicable Me! "It's so fuzzy i'm going to dieee!" Anyways, so my table looks something along the line of this: | post id | parent_id | title | body | date | 1 | NULL | Hello | Hi, i'm K | date 2 | NULL | Thread One | Body One | date 3 | 1 | Hello World | Body One | date 4 | 2 | Thread post 4 | Body One | date 5 | 1 | Thread post 5 | Body One | date 6 | 1 | Thread post 6 | Body One | date 7 | 3 | Hi What's up | Body One | date And here's the PHP code, although it's not very neat I want to clean it up and make it neater. I can only go two level deep so far. Any suggestion or recommendations? Using while & for: // Select * Threads $q = "SELECT * FROM test_db ORDER BY post_id ASC"; $r = @mysql_query($q); while ($pid_row = @mysql_fetch_object($r)) { // Array $pid_arr[] = $pid_row->post_id; // Assign Indexes to Post ID $ppid_arr[] = $pid_row->parent_id; // Assign Indexes to ParentID $md_arr = array($pid_arr, $ppid_arr); // Create multi-dimensional array matrix $parent_id = $pid_row->parent_id; } for ($i = 0; $i < count($pid_arr); $i++) { for ($a = 0; $a < count($ppid_arr); $a++) { $pid = $pid_arr[$i]; // pid = post id $ppid = $ppid_arr[$i]; // ppid = parent id //echo "<div>~~ PID $pid ~~ PPID $ppid ~~</div>"; if ($ppid === NULL) { $ppid_is_null = " & parent_id is NULL"; } else { $ppid_is_null = NULL; } // Select Top level Thread $z = "SELECT * FROM test_db WHERE post_id = '$pid'"; $y = @mysql_query($z); while ($t_row = @mysql_fetch_object($y)) { $title = $t_row->title; // title of child thread $level = $t_row->level; // level of child thread...is this useful? } // Display top level thread lvl 1 if ($ppid === NULL) { // If the parent_id is NULL, display top level thread echo '<div>PID: ' . $pid . ' || PPID: ' . $ppid . " || Title: " . $title . "</div><br>\n"; $post = $pid; // PostID = 1 $parent = $ppid; // Parent ID ex: [1] // Get child id, where parent id = [1] // trying to get the child thread here...but it's not working $child_q = "SELECT * FROM test_db WHERE parent_id = '$post'"; $child_r = @mysql_query($child_q); while($c_row = @mysql_fetch_object($child_r)) { $c_arr[] = $c_row->post_id; $c_ppid_arr[] = $c_row->parent_id; } for ($n = 0; $n < count($c_arr); $n++) { if ($c_ppid_arr[$n] === $post) { echo "<div>$c_arr[$n]</div>"; } } break; //echo "<div>PID: $pid</div>"; } break; } } Using While: <?php require_once('db_connection'); echo '<hr><hr><br>'; // I just realized that selecting * where parent id is null might limit the amount of rows retrieved. // Query to select threads $n = NULL; $q = "SELECT * FROM test_db WHERE (test_db.parent_id is NULL) Order By date ASC"; $r = @mysql_query($q); while ($threads = @mysql_fetch_object($r)){ $pid = $threads->post_id; $sid = $threads->subject_id; $parent_id = $threads->parent_id; $title = $threads->title; $body = $threads->body; echo '<div>PostID: ' . $pid . ' || Parent: ' . $parent_id . ' || SubjectID: ' . $sid . ' || Title: ' . $title . ' || Body: ' . $body . '</div>'; $q2 = "SELECT * FROM test_db WHERE parent_id = '$pid' Order by date DESC"; $r2 = @mysql_query($q2); while ($level2 = @mysql_fetch_object($r2)) { $level2_pid = $level2->post_id; $level = 1.5 *($level2->level); // lvl 2: 3em echo '<div style="text-indent:' . $level . 'em">' . 'PostID: ' . $level2->post_id . ' || ParentID: ' . $level2->parent_id . '</div>'; $q3 = "SELECT * FROM test_db WHERE parent_id = '$level2_pid'"; $r3 = @mysql_query($r3); while ($level3 = @mysql_fetch_object($r3)) { $level3 = 1.5 + $level; echo '<div style="text-indent:' . $level3 . 'em">' . 'PostID: ' . $level3->post_id . ' || ParentID: ' . $level3->parent_id . '</div>'; } } } ?> I'm not a comp. sci major or anything, so I'm learning this as I go. Any help would be greatly appreciated. It seems like the while & for is more practical, but i'm not quiet sure. What am I doing wrong? - K I just joined this forum today ^_^ Hope to be good friends with you guys and gals Folks, I have an Array as shown in the below Structre (An array has multiple parents and childs) Array $productlist Quote Array { 1 => A 2 => B 3 => C } Array { 1 => A 2 => B 3 => C 4 => D 5 => E } Array { 1 => A 2 => B 3 => C 4 => D 5 => E 6 => E 7 => E 8 => E } $productlist Array can have N numbers of Parents array as shown in above example, (above its 3 it can be anything). All i want is, i want to print_r only the last Parent rray and all its child elements. So in this case it will be: Quote Array { 1 => A 2 => B 3 => C 4 => D 5 => E 6 => E 7 => E 8 => E } HOw can i achieve this with PHP, i tried even count() but its not working not even array_pop(). Can someone help me with this? Regards, Natasha Hello all, I have some piece of code that is nested like this $variable = 'This is a global argument'; function parentFunction($variable) { function childFunction() { echo 'Argument of the parent function is '.$GLOBALS['variable']; } childFunction(); } parentFunction(5); What I want to know is - Is there a way to access a variable from the parent function without passing arguments to the child function? (Something like how classes have parent::?). I don't want to use $GLOBALS because it might cause some variable collision, and I didn't want to pass arguments because incase I decide to change the arguments in the parent function I'd have to do it in the child function aswell. From my searching around in the Internet it seems like this is not possible, but if theres a slight chance that there might be something out there, i'm willing to give it a shot . Thanks in advance Hello Guys, Need a little help here. I have a db structure like this cat_id | cat_name | cat_status | parent_id 1 First Test 1 0 2 Just testing 1 0 4 Books 1 2 5 Cars 1 0 6 Ford 1 5 If the parent_id = 0 it is considered to be the parent. If it is a number it is considered a child and referencing the parent I want to be able to query the database and grab the cat and the sub cat and echo it on my page. Its like a classified ads application. Here is my while loop that I currently have which only echo's out the parent category. I would like to echo the child category under the respective parent category. I think I would have to do a loop within a loop, but not sure how to do it.. $query = "SELECT * FROM ad_category WHERE cat_status='1' && Parent_id='0' ORDER BY cat_name"; $result = mysql_query($query); while($row = mysql_fetch_row($result)) { $cat_name = $row[1]; $cupper = UCWords($cat_name); echo $cupper . "<br>" ; } Thanks for your help in advance Hey guys! I have the following strange problem: Listing 1: echo $n; // Result is 20167 ! if($child->id == $n){ $image = array(); $image[] = '"' . $child->id . '"'; $image[] = '"' . $child->name . '"'; $image[] = '"' . $misc->clean_path($child->file) . '"'; $image[] = '"' . $child->file_name . '"'; $image[] = '"' . $child->file_type . '"'; $image[] = '"' . $path . '"'; $images[] = implode("\t", $image); } The if-statement is not true... so probably there's no $child->id with value 20167.... but watch this: Listing 2: if($child->id == 20167){ $image = array(); $image[] = '"' . $child->id . '"'; $image[] = '"' . $child->name . '"'; $image[] = '"' . $misc->clean_path($child->file) . '"'; $image[] = '"' . $child->file_name . '"'; $image[] = '"' . $child->file_type . '"'; $image[] = '"' . $path . '"'; $images[] = implode("\t", $image); } Now with the hard coded value 20167 the statement is true and gives one result.... Strange, isn't it? I placed the following three functions/test direct before the if-statement: var_dump($n); Result: NULL echo $n Result: 20167 echo "{$n}"; Result: I tested one function at a time. How can this happen? Thanks to all! :-) Hi to all,
As per my client suggested, i need to change the info box background color for every info box (circular way). So i used the CSS3 pseudo nth-child algoritham to assign each info box background color with different background colors.
Here is my html code
<div class="row flexslider carousel" id="appList"> <ul class="slides"> <li> <div class="col-lg-3 col-md-6 col-sm-6"> <div class="info-box"> <img src="img/shortcuts/money.png" alt=""> <div class="count">1</div> <div class="title">New users</div> <div class="desc">Purchase</div> <div class="desc f-bold">Test</div> </div> </div> </li> <li> <div class="col-lg-3 col-md-6 col-sm-6"> <div class="info-box"> <img src="img/shortcuts/money.png" alt=""> <div class="count">2</div> <div class="title">New users</div> <div class="desc">Purchase</div> <div class="desc f-bold">Test</div> </div> </div> </li> <li> <div class="col-lg-3 col-md-6 col-sm-6"> <div class="info-box"> <img src="img/shortcuts/money.png" alt=""> <div class="count">3</div> <div class="title">New users</div> <div class="desc">Purchase</div> <div class="desc f-bold">Test</div> </div> </div> </li> <li> <div class="col-lg-3 col-md-6 col-sm-6"> <div class="info-box"> <img src="img/shortcuts/money.png" alt=""> <div class="count">4</div> <div class="title">New users</div> <div class="desc">Purchase</div> <div class="desc f-bold">Test</div> </div> </div> </li> <li> <div class="col-lg-3 col-md-6 col-sm-6"> <div class="info-box"> <img src="img/shortcuts/money.png" alt=""> <div class="count">5</div> <div class="title">New users</div> <div class="desc">Purchase</div> <div class="desc f-bold">Test</div> </div> </div> </li> </ul> </div>Here is CSS code .info-box { min-height: 140px; border: 1px solid black; margin-bottom: 30px; padding: 20px; color: white; -webkit-box-shadow: inset 0 0 1px 1px rgba(255, 255, 255, 0.35), 0 3px 1px -1px rgba(0, 0, 0, 0.1); -moz-box-shadow: inset 0 0 1px 1px rgba(255, 255, 255, 0.35), 0 3px 1px -1px rgba(0, 0, 0, 0.1); box-shadow: inset 0 0 1px 1px rgba(255, 255, 255, 0.35), 0 3px 1px -1px rgba(0, 0, 0, 0.1); } .info-box i { display: block; height: 100px; font-size: 60px; line-height: 100px; width: 100px; float: left; text-align: center; border-right: 2px solid rgba(255, 255, 255, 0.5); margin-right: 20px; padding-right: 20px; color: rgba(255, 255, 255, 0.75); } .info-box img { display: block; height: auto; font-size: 46px; line-height: 46px; width: auto; float: left; text-align: center; border-right: 2px solid rgba(255, 255, 255, 0.5); margin-right: 20px; padding-right: 20px; color: rgba(255, 255, 255, 0.75); } .info-box .count { margin-top: -10px; font-size: 34px; font-weight: 700; } .info-box .title { font-size: 12px; text-transform: uppercase; font-weight: 600; } .info-box .desc { margin-top: 10px; font-size: 12px; } #appList ul.slides li div div.info-box:nth-child(5n+1) { background: #fabb3d; border: 1px solid #f9aa0b; } #appList ul.slides li div div.info-box:nth-child(5n+2) { background: #ff5454; border: 1px solid #ff2121; } #appList ul.slides li div div.info-box:nth-child(5n+3) { background: #67c2ef; border: 1px solid #39afea; } #appList ul.slides li div div.info-box:nth-child(5n+4) { background: #79c447; border: 1px solid #61a434; } #appList ul.slides li div div.info-box:nth-child(5n) { background: #20a8d8; border: 1px solid #1985ac; }But when i tried with the above code, the info box only accepts (5n+1) CSS code. Can any one please suggest me the way to get the solution. Hi, I am trying to work with this xml page: http://maps.google.com/maps/api/directions/xml?origin=m20%202nu&destination=m5%205hf&sensor=false public function LoadXml(){ $xml = simplexml_load_file("http://maps.google.com/maps/api/directions/xml?origin=m20%202nu&destination=m5%205hf&sensor=false"); foreach ($xml->xpath('//distance') as $distance): echo $distance->value->getName() . ": " . $distance->value . "<br />"; endforeach; echo "<BR>"; foreach($xml->xpath('//leg') as $address): echo "The start address is: ".$address-> start_address.$address. "<br />"; echo "The end address is: ".$address->end_address.$address; endforeach; } what this code does is echo out the following: Quote value: 102 value: 268 value: 701 value: 103 value: 4512 value: 275 value: 704 value: 1575 value: 64 value: 65 value: 1782 value: 313 value: 10464 The start address is: Manchester, Greater Manchester M20 2NU, UK The end address is: Salford M5 5HF, UK Now i don't need ALL the values, i only need the total value which is 10464. So is there a way to display the last child, or the final value? So all i want to show is value: 10464.. How can i access the final instance of the value? Thanks again I have the following result that I am getting from a source. Code: [Select] SimpleXMLElement Object ( [CategoryID] => 1 [Name] => Other [Order] => 0 [link] => http://www.link.com?sub=1 ) SimpleXMLElement Object ( [CategoryID] => 1233916011 [Name] => ceramic [Order] => 1 [ChildCategory] => SimpleXMLElement Object ( [CategoryID] => 1234016011 [Name] => dish [Order] => 1 ) [link] => http://www.link.com?sub=13476 ) SimpleXMLElement Object ( [CategoryID] => 1233917011 [Name] => laminate [Order] => 2 [link] => http://www.link.com?sub=98247 ) I need to get it into a database with the following structure Code: [Select] id categoryID cName cOrder clink cparent By using Code: [Select] foreach($this->resp->Store->CustomCategories->CustomCategory as $cat) { $sub = $cat->CategoryID; $ord = $cat->Order; $linkto = "$stlink?fsub=$fsub"; $nm = htmlspecialchars($cat->Name); $par=$cat->ChildCategory->Order; $query = "INSERT INTO Cat (categoryID,cName,cOrder,clink,cparent) VALUES ('$sub','$nm','$ord','$linkto','$par')"; $result = @mysql_query ($query); // Run the query. } I can get Code: [Select] id categoryID cName cOrder clink cparent 1 1 Other 0 http://www.link.com?sub=1 0 2 1233916011 ceramic 1 http://www.link.com?sub=13476 0 2 1233917011 laminate 2 http://www.link.com?sub=98247 0 But I need to get the ChildCategory in there w/ cparent like Code: [Select] id categoryID cName cOrder clink cparent 1 1 Other 0 http://www.link.com?sub=1 0 2 1233916011 ceramic 1 http://www.link.com?sub=13476 0 3 1234016011 dish 1 1 <--- like this 4 1233917011 laminate 2 http://www.link.com?sub=98247 0 any help appreciated... |