PHP - Return Array From Mysql
Hello.
I'm new to php and need a little help please. I try to build a class that return an Array of all the table in my db. and be able to get all the data by there col name (like username, password....) but all i got is the last record from the db. here is the class: <?php class db{ function getall($table, $search){ $sql = "SELECT ". $search ." FROM " . $table; $result = mysql_query($sql) or die('Error, insert query failed' . mysql_error()); while($row=mysql_fetch_assoc($result)){ $data = $row; } return $data; } and this is in the html page: $data = $db->getall("users", "*"); foreach($data as $row){ echo $row['fullname']; echo "<BR>"; } can anybody help me with that? Similar TutorialsHi everyone for my end of studies projects I decided to do a little e-commerce problem on the filter .. I use an ajax request at the click of the checkbox this goes to my controller which calls a method of my Model class but the concern is that .. if the array $ _POST ['brands'] has several elements then only the last one is returned to me? I thought I saw one day that if the same variable is in a url then the last value will be returned to me is for security but how can I do ... I have been there for too long .. and finally despair. . Help me please... :') request payload: brands%5B%5D=arai&brands%5B%5D=bell reply :
<- prepare var_dump ()
string (4) "arai" <- bind
var_dump () of my fetchAll () since the last value taken into account is bell then I get two items of the bell brand from my bdd but no arai ... Edited October 24, 2020 by jcb789error phpfreaks I am querying a database using pdo but I keep getting an array that returns two results. As you can see from the array below it returns the id and result and then repeats the result . I only want the keys with text to be returned. Any help would be great. Code: [Select] ( [0] => Array ( [Ticket_ID] => 2 [0] => 2 [Customer_id] => 1 [1] => 1 [Business_Name] => [2] => my database method is Code: [Select] private function queryFetchAllPDO($query) { try { $this->dataObj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sth = $this->dataObj->prepare($query); $sth->execute(); echo"I am here"; $result = $sth->fetchAll(); print_r($result); // $stmt = $this->dataObj->query($query); // $stmt->setFetchMode(); // $result = $stmt->fetchAll(); } catch (PDOException $e) { $e->getMessage(); } return $result; } and the query method is Code: [Select] private function clieViewHome() { //find user id $sql = "SELECT Customer_id FROM customer WHERE Username='" . $this->user . "'"; $sessAccess = $this->connection->getQueryFetchPDO($sql); foreach ($sessAccess as $value) { $userID = $value; } //place into query $sql = "SELECT * FROM tickets WHERE Customer_id ='" . $userID . "'"; $tableArr = $this->connection->getQueryFetchAllPDO($sql); print_r($tableArr); foreach ($tableArr as $key => $value) { $return .= "<tr>\n"; foreach ($tableArr[$key] as $value2) { $return .="<td>" . $value2 . "</td>\n"; } $return .= "</tr>\n"; } return $return; } Hi,Dear Frnds...........................I Hope U r all fine. I am using php.Here is the problem in the Return array from function. This is the code. Code: [Select] <?php $store = array(); $test = get_my_links(); print_r($store); function get_my_links() { $my_array = array('e','f','g'); foreach($my_array as $key=> $list) { $store[] = $list; } return $store; } ?> Suppose the array is maked dynamically. please help me..THANKS... hello. im trying to get some results from a db and all i keep getting is the word ARRAY ?? I want to get all the placeholders that relate to a page. so if pageID=1 has place holder 1, place holder 2 and place holder 3 it will return 1, 2, 3 etc... in the db i have id pageID phNumber 1 1 1 2 1 2 3 1 3 etc.. this is the code i have Code: [Select] public function find_placeholders($pageID=0){ $sql = "SELECT phNumber FROM ".self::$table_name." WHERE pages_id=".$pageID.""; $result_array = self::find_by_sql($sql); return $result_array; } and on the page i have.. Code: [Select] <?php echo Placeholders::find_placeholders($pageID); ?> all i get is Quote Array once i solve this problem i will want to use each number in the array to find the content for each. so if i get 1,2,3 i will try and do some thing like. foreach placeholder number echo elements but 1 step at a time thanks for any help rick I need to return a specific key from the object converted to array but it seems that it dosent work Code: [Select] $toarray = (array)$tmp; $name = array_keys($toarray,'name'); print_r($toarray); print:Array ( [id] => 9 [name] => dfd [text] => fdsf [rating] => 0 [totalv] => 0 ) and when i try to return the key Code: [Select] print_r($name); Array ( => rating [1] => totalv ) But I only need the key whit the 'name' value I am trying to write a program that sends out a newsletter but I am lost at returning an array of emails. This is what I have
<?php require("../PHPMailer/class.phpmailer.php"); include 'includes.php'; $mail = new PHPMailer; $subject = $_POST['subject']; $text = $_POST['newsletterBody']; $unsubscribe = "<br /><br /><br /><br />If you would no longer like to receive these emails, please <a href='removeemail.php'>Click Here</a> to unsubscribe."; $mail->IsSMTP(); // Set mailer to use SMTP $mail->Host = 'localhost'; // Specify main and backup server $mail->Port = '465'; $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = '****EMAIL ADDRESS****'; // SMTP username $mail->Password = '****EMAIL PASSWORD*****'; $mail->SMTPAuth = true; $mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted $mail->From = '****EMAIL ADDRESS****'; $mail->FromName = '****NAME****'; $mail->AddAddress('****EMAIL ADDRESS****', '****NAME****'); $email = getEmail("", $DBH); foreach ($email as $newEmail) { $addEmail = $newEmail['email_addr']; $mail->AddAddress($addEmail); $DBH = null; } $mail->AddReplyTo('****EMAIL ADDRESS****', '****NAME****'); $mail->WordWrap = 50; // Set word wrap to 50 characters $mail->IsHTML(true); // Set email format to HTML $mail->Subject = $subject; $mail->Body = $text . "<br /><br /><br /> To unsubscribe to this email please <a href='www.raven-consult.com/newsletter_remove.php'>Click Here</a>"; $mail->AltBody = $text; if(!$mail->Send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; exit; } echo "Message has been sent <a href='newsletter.php'>Return back</a>"; ?>This is the portion of the includes file that you need to know. function getEmail($inId, $DBH) { if (!empty($inId)) { $blogstmt = $DBH->prepare("SELECT email_addr FROM newsletter_emails WHERE id = :userId"); $blogstmt->bindParam(":userId", $inId); $blogstmt->execute(); $postArray = $blogstmt->fetchAll(PDO::FETCH_ASSOC); } else { $blogstmt = $DBH->prepare("SELECT * FROM newsletter_emails"); $blogstmt->execute(); $postArray = array(); $results = $blogstmt->fetchAll(PDO::FETCH_ASSOC); foreach($results as $row){ $myPost = new nlEmails($row['id'], $row['email_addr'], $DBH); array_push($postArray, $myPost); } } return $postArray; $DBH = null; } class nlEmails { public $id; public $email; function __construct($inId=null, $inEmail=null, $DBH) { if(!empty($inId)) { $this->id = $inId; } if(!empty($inEmail)) { $this->email = $inEmail; } } }When I try and submit the newsletter to be sent out all I get back is this error. "Cannot use object of type nlEmails as array ......" Hey all I am just now getting around to the newest version of the PHP sdk for Facebook. It seems to use a new array of returned data that I can not seem to be able to parse out what I need and not all other gibberish it has contained inside the array.
The array returned looks like this: Array ( [data] => Array ( [0] => stdClass Object ( [id] => 439676913452345546787863523525 [name] => John Doe [picture] => stdClass Object ( [data] => stdClass Object ( [is_e] => [url] => https://blah.com.... ) ) ) [1] => stdClass Object ( [id] => 56594790468026754634524674 [name] => Bob Barker [picture] => stdClass Object ( [data] => stdClass Object ( [is_e] => [url] => https://blah.com.... ) ) ) [2]...etc etc... [paging] => stdClass Object ( [cursors] => stdClass Object ( [before] => QWFMmhllXN5JH....Rk52QWc= [after] => WGHtdnNIwaDlRz....05RNB0E= ) ) ) )In the older version of the Facebook SDK I just needed to do something along these lines (below code example is getting the id within the returned array and checking also to make sure it has a value or not): foreach($theReturnedArray['data'] as $rData) { $id = (isset($rData['id']) ? $rData['id'] : null); $name = (isset($rData['name']) ? $rData['name'] : null); echo $name . ' ' . $id . '<br />'; }in order to get the value that I needed. I have also tried: foreach($graphObject['data'] as $rData) { echo $rData->id + '<br/>'; echo '======================================<br/>'; }and that just gives me 0's for each one it finds.. Now the return has an added stdClass object within the array itself and I am unsure on how to go about getting id, name & picture url from it. Any help would be awesome! SELECT field, (array of values from table 2) FROM $table1 t1 LEFT JOIN $table2 ON t1.id=t2.id ... is something like this possible? (where I return records from t1 in a LEFT JOIN, but also get an array of any of the fields/records from the table 2) I'm not versed in PHP OOP and I have some code that I need to echo out onto a page. I don't know what the meaning of $ct->something is in this code. Is this an array of some type? How do I echo out the $ct->title onto another page? Use a function call? I just don't know what all of the $ct variables are and how to get to them. Any help is appreciated. Code: [Select] function current_theme_info() { $themes = get_themes(); $current_theme = get_current_theme(); if ( ! isset( $themes[$current_theme] ) ) { delete_option( 'current_theme' ); $current_theme = get_current_theme(); } $ct->name = $current_theme; $ct->title = $themes[$current_theme]['Title']; $ct->version = $themes[$current_theme]['Version']; $ct->parent_theme = $themes[$current_theme]['Parent Theme']; $ct->template_dir = $themes[$current_theme]['Template Dir']; $ct->stylesheet_dir = $themes[$current_theme]['Stylesheet Dir']; $ct->template = $themes[$current_theme]['Template']; $ct->stylesheet = $themes[$current_theme]['Stylesheet']; $ct->screenshot = $themes[$current_theme]['Screenshot']; $ct->description = $themes[$current_theme]['Description']; $ct->author = $themes[$current_theme]['Author']; $ct->tags = $themes[$current_theme]['Tags']; $ct->theme_root = $themes[$current_theme]['Theme Root']; $ct->theme_root_uri = $themes[$current_theme]['Theme Root URI']; return $ct; } I hate array... 😞 So I had a block of code inside my photo-gallery.php script that took the path to my photos directory, and went to that directory, and then read all of the photo filenames into an array. Then in my HTML, I iterate through this array to display all of the photos for my gallery. Now I would like to move that code to an included file so multiple scripts can access it and always be working with the same array. It seems to me that I need to encapsulate my code inside a function? Then I could call my getPhotoFilesArray back to my callings cript, and use that array for whatever. I haven't coded PHP in like 4 years and I am struggling to return the entire array back to my caling script. This is what I have so far... function getPhotoFilesArray($photoPath){ $photoFiles = array(); <code to find corresponding files> $photoFiles gets populated in a loop return $photoFiles; }
Then in my calling script, I have... <?php require_once('../../../secure_outside_webroot/config.php'); require_once(WEB_ROOT . 'utilities/functions.php'); getPhotoFilesArray($photoPath); var_dump($photoFiles);
I get some error...
Notice: Undefined variable: phtoFiles in photo-gallery.php line 133 (which is my var_dump).
<br> Would appreciate help getting this to work!
Edited December 6, 2019 by SaranacLake Hey guys, So im building a Content Management System for my A2 project in Computing, and i have a dataBase class. Now, i can return one thing, or do things like inserts however im having a problem returning a list of things such as: dataBase.class.php Code: [Select] public static function getNYCPost($table, $limit) { dataBase::_dbConnect(); if($limit == 0) { //debug: echo 'in as 0'; $data = mysql_query("SELECT id, linklabel FROM ".$table." WHERE showing='1' AND id >= 2"); } if($limit == 1) { //debug: echo 'in'; $data = mysql_query("SELECT id, linklabel FROM ". $table ." WHERE showing='1' AND id >= 2 ORDER BY id DESC LIMIT 5"); return $data; } } When i try to do this in the main code: index.php Code: [Select] <?php $list = dataBase::getNYCPost($pages,1); // echo $list; while ($row = mysql_fetch_array($list)) { $pageId = $row["id"]; $linklabel = $row["linklabel"]; $menuDisplay .= '<a href="index.php?pid=' . $pid . '">' . $linklabel . '</a><br />'; } echo $menuDisplay; ?> $list doesnt return anything, the previous method i used in the class was to make a list and an array and put the contents of the query in an array like: Code: [Select] list($list[] = $row); or something i cant quite remember i saw a youtube video tutorial and it worked for them, but it wasnt for me. If anyone knows how i can return various rows from a database it would be appreciated Thanks. My tree gather function gives me multidimensional array. However i want it to be one dimensional . I was getting one dimensional earlier however i forgot how i got it. Can someone please tell me my mistake Code Code: [Select] <?php include'config.php'; function tree_gather($node) { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild']) || !empty($array['rchild'])) { $child[] = $array['lchild']; $child[] = $array['rchild']; $eh[] = tree_gather($array['lchild']); $child = array_merge($child, $eh); $eh1[] = tree_gather($array['rchild']); $child = array_merge($child, $eh1); } return $child; } $pair = tree_gather(1000000); echo "<pre>"; print_r($pair); echo "</pre>"; ?> Output Code: [Select] Array ( [0] => 3632873 [1] => 5951538 [2] => Array ( [0] => 8930480 [1] => 7563232 [2] => Array ( [0] => 1144744 [1] => 4386810 [2] => [3] => ) [3] => ) [3] => ) Hi Guys, I'm trying the following.. returning an array from a php function to Ajax success but the alert seems to only display undefined. PHP Code: [Select] public function reply() { $item_id = $this->uri->segment(3); $type = $this->uri->segment(4); if($type == 1){ $data['get_news_item'] = $this->Newsletter_model->get_news_item($item_id); $test = array( "Paul", "Mike"); return $test; } } AJAX Code: [Select] $.ajax({ type: "POST", url: "<?php echo site_url(); ?>newsletter/reply/"+id+"/"+type, cache: false, success: function (data){ alert(data[0]); // So this should display "Paul"? }); [/code] Hi. I'm making a registration form, that will put each entered item into $_POST, which will then submit to the same page. First, I need to has the password with this method: Code: [Select] <?php public function hash_password($password) { $result = hash(sha512, $password . SALT); return $result; } >?then prepare the entered data for mysql with this method: Code: [Select] <?php public function query_prep($value) { $result = $this->real_escape_string($value); if (!$result) { die("Preparing query failed: " . $this->errno); } return $result; } ?> However, how can I "validate" the form. I need to pass the now prepared $_POST array into a loop, that executes the prepare method on each item in the array and then puts it in an array again. Also, how could I do some kind of function that checks if all required fields were filled, and how I can fail the submission if invalid characters were used. I've done pretty much everything I can come up with. The method itself works fine, if I print_r(); just before returning it, it successfully returns the array. But once returned, it's empty. Heres my code: Code: [Select] <?php include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_database.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/values.php"; ?> <?php class User { private $database; public function __construct(MySqlDatabase $database) { //Type Hinting $this->database = $database; } public function hash_password($password) { $result = hash(sha512, $password . SUOLA); return $result; } public function find_all() { $result = $this->database->db_query("SELECT * FROM users"); $final = mysqli_fetch_array($result); return $final; } public function find_by_id($id=1) { $result = $this->database->db_query("SELECT * FROM users WHERE id={$id}"); $final = mysqli_fetch_array($result); return $final; } public function check_required($array) { // this method gets called first if (empty($array['username']) || empty($array['first_name']) || empty($array['last_name']) || empty($array['password']) || empty($array['email']) || empty($array['secret_question']) || empty($array['password2']) || empty($array['secret_answer']) || !($array['email'] === $array['email2']) || !($array['password'] === $array['password2'])) { die("Fill required fields!" . "<br />" . "<a href='javascript:history.go(-1)'>Go back</a>"); } else { $this->database->array_query_prep($array); // it then continues to the next method automatically } } public function create_user($array) { $date = date('d-m-Y H:i:s'); $sql = "INSERT INTO users (username, first_name, "; $sql .= "last_name, password, email, secret_question, "; $sql .= "secret_answer, create_time) VALUES "; $sql .= "('{$array['username']}', '{$array['first_name']}', '{$array['last_name']}', "; $sql .= "'{$array['password']}', '{$array['email']}', '{$array['secret_question']}', '{$array['secret_answer']}', "; $sql .= "'{$date}');"; $this->database->db_query($sql); } } ?> Code: [Select] <?php include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/values.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_user.php"; ?> <?php class MySqlDatabase extends MySQLi { function __construct() { //Check if constants are missing if (!defined("DB_USERNAME") || !defined("DB_SERVER") || !defined("DB_PASSWORD") || !defined("DB_NAME")) { die("One or more of the database constants are missing!"); } //Establish connection if constants are present using the parent class parent::__construct(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); //Echo error message if connection has failed if ($this->connect_errno) { die("Database connection has failed: " . $this->connect_errno); } } public function db_query($sql) { $result = $this->query($sql); if (!$result) { die("Database query failed: " . $this->errno); } } public function array_query_prep($array) { // continues to this method $result = array_map(array($this, 'real_escape_string'), $array); if (!$result) { die("Preparing query failed: " . $this->errno); } // if i print_r here, it returns the array as it should return $result; } } ?> Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" type="text/css" href="../stylesheets/main.css"/> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body class="main_body"> <div id="container"> <div id="header"> <div id="top"> <div id="login"> <form action="" method="post" target="/login/"> <label for="username">Username:</label><br /> <input name="username" type="text" class="text" maxlength="20" /><br /> <label for="password">Password:</label><br /> <input name="password" type="password" class="text" maxlength="30" /><br /> <input name="submit" type="submit" class="loginbtn" value="Login" /></form> </div> </div> <div> <h1>Welcome to _________ website!</h1> </div> <?php include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/values.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/functions.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_database.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_user.php"; ?> <?php $database = new MySqlDatabase(); $user = new User($database); if (isset($_POST['submit'])) { $result = $user->check_required($_POST); //this is where I get nothing back $user->create_user($result); die("Registration was successful!"); } else { $username = ""; $first_name = ""; $last_name = ""; $password = ""; $email = ""; $email2 = ""; $secret_question = ""; $secret_answer = ""; unset($_POST); } ?> <form action="" method="post" target="_self"> Username: <input type="text" name="username" class="text" maxlength="20" value="<?php echo htmlentities($username); ?>" /><br /> First Name: <input type="text" name="first_name" class="text" maxlength="20" value="<?php echo htmlentities($first_name); ?>" /><br /> Last Name: <input type="text" name="last_name" class="text" maxlength="20" value="<?php echo htmlentities($last_name); ?>" /><br /> Password: <input type="password" name="password" class="text" maxlength="30" value="<?php echo htmlentities($password); ?>" /><br /> Enter again: Password: <input type="password" name="password2" class="text" maxlength="30" value="<?php echo htmlentities($password2); ?>" /><br /> Email: <input type="text" name="email" class="text" maxlength="30" value="<?php echo htmlentities($email); ?>" /><br /> Enter again: Email: <input type="text" name="email2" class="text" maxlength="30" value="<?php echo htmlentities($email2); ?>" /><br /> Secret Question: <input type="text" name="secret_question" class="text" maxlength="35" value="<?php echo htmlentities($secret_question); ?>" /><br /> Secret Answer: <input type="text" name="secret_answer" class="text" maxlength="35" value="<?php echo htmlentities($secret_answer); ?>" /><br /> <input type="submit" name="submit" class="submitbtn" value="Submit" /> <?php ?> </div> </div> </body> </html> [/quote] Any ideas? Hi! So what I'm trying to do is split a multi dimensional array of strings ( each containing 3 strings inside of 1 array ) so I can write the results to a file. So say I had a bunch of strings inside 1 array : class File { function WriteFile ( $filename, $content ) { $list = [ $content ]; $delimiters = File :: checkDelimiter ( $content, true, false ); $fp = fopen ( $filename, 'w' ); foreach ( $list as $fields ) { $fields = File :: SplitFileByDelimiter ( $fields, ",", 3 ); file_put_contents ( $filename, $fields ); } fclose ( $fp ); } } $file-> File :: WriteFile ( $filepath . $filename, "TEST!, TEST!, TEST!, " . "TEST!, TEST!, TEST!, " . "TEST!, TEST!, TEST!" ); Instead of writing : TEST!, TEST!, TEST!, TEST!, TEST!, TEST!, TEST! ,TEST!, TEST!, TEST! to the file in a straight line, it should write it like this : TEST!, TEST!, TEST!, TEST!, TEST!, TEST!, TEST!, TEST!, TEST! Any help is ABSOLUTELY appreciated! Edited May 22 by AquariaXI hello, i seem to be stuck again and this bug is difficult for me to solve.
if(isset($_POST['boards'])) $boards[] = $_POST['boards']; $allboards = implode("",$boards[0]); echo $allboards;outputs (browser source)... hello world I have a combobox with the "multiple" property. when two items are selected, the combobox "name" property has an array that passes to the $_POST variable. what i would like is those two words to be displayed on the same line. I have tried rtrim($var, "\r\n") but that does nothing. the reason i need them on the same line is because i would change then to "hello, world" and then add them as a mysql query, for example... $query = "SELECT hello, world FROM table... I'm trying to return to array of letters that bruteForce finally decides upon. However, I can't seem to pass the array to librarySolve. I'm feeling dumb, any help? Code: [Select] function librarySolve($string){ $temp = $this->bruteForce($string, FALSE, 0); return $temp; } function bruteForce($string, $state, $trys){ $base = $string; $state = $state; $new_letters = array(); if($trys <= 6000){ $this->new_letters = $this->generateRandomCipher(); $string = preg_replace('/[^a-zA-Z0-9-\s]/', '', $string); for($a=0;$a<=strlen($string);$a++){ $letter = substr($string, $a, 1); $pattern = "/[A-Z]/"; if(preg_match($pattern, $letter)!=0){ $new_letter = $this->new_letters[$letter]; } else if(preg_match($pattern, $letter)==0) { $new_letter = $letter; } $decipher .= $new_letter; } $word_array = explode(" ", $decipher); $count = 0; for($a=0;$a<count($word_array);$a++){ $do = $this->checkWord($word_array[$a]); if(!empty($do)){ $count++; } } if($count>=2){ $state = TRUE; } else { $state = FALSE; } if($state==TRUE){ return $this->new_letters; } else { $trys++; $this->bruteForce($base, $state, $trys); } } } Hello, My current server setup :
PHP version: 7.1.4
From what I read, in order to have MySQL return native datatypes (as opposed to just strings) : Now, I do have mysqlnd, but a simple PDO Prepared statement still returns me all strings, even though some columns are set as INT, VARCHAR, DATETIME, etc.. $stmt = $pdo->prepare("SELECT * FROM tbl_users WHERE id=1"); $stmt->execute(); $user = $stmt->fetch(); var_dump($user); OUTPUT: array(13) { ["id"]=> string(1) "1" ["is_admin"]=> string(1) "1" ["is_active"]=> string(1) "1" ["username"]=> string(5) "jdoe" ... }
I'm not sure what to look for to resolve this issue if I want it to return INT as INT and not STRING, etc. Does having `extension_loaded('mysqlnd') == true`, make my system automatically use this native mysql driver? How can I tell ? Could this be a version problem perhaps?
Much thanks! Pat
Hi, I have a multidimensional array where each array has a parent id node to create a hierarchical tree. $hierarchy[] = array('id' => 1, 'parent_id' => 0, 'name' = 'root1'); $hierarchy[] = array('id' => 2, 'parent_id' => 0, 'name' = 'root2'); $hierarchy[] = array('id' => 3, 'parent_id' => 1, 'name' = 'root1-1'); $hierarchy[] = array('id' => 4, 'parent_id' => 1, 'name' = 'root1-2'); $hierarchy[] = array('id' => 5, 'parent_id' => 3, 'name' = 'root1-1-1'); $hierarchy[] = array('id' => 6, 'parent_id' => 2, 'name' = 'root2-1'); I'm trying to come up with a recursive key/value search routine that will return all ancestor arrays of the found item without knowing the depth of the tree. All nodes with 0 for the parent_id are root level nodes. Basically I want to search for something like "where key = name and value = xxx" and have it return all ancestors of that node. So if I wanted to search for "key = name and value = root1-1", it should return and array like: array[0] = array('id' => 1, 'parent_id' => 0, 'name' = 'root1'); //parent node first array[1] = array('id' => 3, 'parent_id' => 1, 'name' = 'root1-1'); //first child after parent if I was to search for "key = name and value = root1-1-1", it should return: array[0] = array('id' => 1, 'parent_id' => 0, 'name' = 'root1'); //parent node first array[1] = array('id' => 3, 'parent_id' => 1, 'name' = 'root1-1'); //first child after parent array[2] = array('id' => 5, 'parent_id' => 3, 'name' = 'root1-1-1'); //first grandchild So the main problem comes in the iteration and keeping track of parents. If I just want the array with the answer I can get that node, but I can't get it with all of the ancestors attached. How would you go about this? Any good ideas out there? Thanks! |