PHP - Want My Function To Return One Dimensional Array.
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] => ) Similar TutorialsHi,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... 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 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); } } } I have a for loop which extracts info from a MySQL table, chooses something then needs to push each bit into an array: for($i = 0 ; $i < $query_report_rows ; ++$i) { $row= mysql_fetch_row($query_names); if($row[6] == 0) { $sName = $row[1]; } elseif($row[6] == 1) { $sName = $row[2]; } $name = "$row[0], $sName"; $print = nl2br($row[7]); } What i need is a multidimensional array to hold $name and $print: $name_print = array( array('name'=>$name 'print'=>$print ) ) How do i array push into such an array from the above for loop? (multi-dimensional array are a very weak point at the moment, so any pointers here would be very much appreciated) Hiya peeps! Here are my scripts; test.php <?php include 'formValidation.php'; $new = new formValidation( array( array( 'formname' => 'firstname', 'value' => 'james', 'options' => 'required, alllowercase, onlyletters', 'name' => 'First Name' ), array( 'formname' => 'password', 'value' => 'blahblah', 'options' => 'required, oneuppercase, alphanumerical', 'name' => 'Password' ), array( 'formname' => 'username', 'value' => 'blahblah', 'options' => 'required, oneuppercase, alphanumerical', 'name' => 'Username' ) ) ); ?> formValidation.php <?php class formValidation { private $inputs; function __construct($inputs = array()) { foreach($inputs as $input_key => $input_value) { foreach($input_value as $key => $value) { echo $value . '<br />'; } } } public function __prep($formname, $options, $value, $name) { echo $formname . ' ' . $options . ' ' . $value . ' ' . $name . '<br />'; } } ?> This outputs; firstname james required, alllowercase, onlyletters First Name password blahblah required, oneuppercase, alphanumerical Password username blahblah required, oneuppercase, alphanumerical Username But what i need to do is for every four values I need them to be sent to the __prep function. EG; $this->__prep('firstname', 'required, alllowercase, onlyletters', 'james', 'First Name'); I have no idea how to do this tho, I have tried a for() loop, another foreach loop, array the first four values then foreaching them again. I'm stuck, someone please help! Many thanks, James. Hi, I have a question: I have a CSV file where the first row are the names of the columns. The format of the CSV file is: Name | Surname | Adress | Date of birth Robert | Miller | Athome 1| 29. Februar 1976 . . . How should I import the CSV. Thanks in advance. I am having a hell of a time getting this to work. I need the keys in an array to be specific, not a sequential number or a row in my database. I need to add to the array through each loop of my while() statement. This code does it, but does not use the keys I specify, after the first entry, it starts assigning numbers to keys. Any guidance would be great. <?php require_once ('includes/config.php'); require_once ('includes/connect.php'); $echoarray = array(); $resultsql = mysql_query("SELECT * FROM clients")or die(mysql_error()); while($row = mysql_fetch_array($resultsql)){ if(empty($echoarray)){ $echoarray = array( 'id' => $row['ID'], 'name' => $row['First_Name'] . " " . $row['Last_Name'], 'price' => $row['Status'], 'number' => $row['Sex'], 'address' => $row['Phys_Street'], 'company' => $row['Agency'], 'desc' => $row['Notes'], 'age' => $row['Date_Birth'], 'title' => $row['Occupation'], 'phone' => $row['Phone'], 'email' => $row['Email'], 'zip' => $row['Phys_Zip'], 'country' => $row['Phys_City'] ); } else { array_push($echoarray, $echoarray['id'] = $row['ID'], $echoarray['name'] = $row['First_Name'] . " " . $row['Last_Name'], $echoarray['price'] = $row['Status'], $echoarray['number'] = $row['Sex'], $echoarray['address'] = $row['Phys_Street'], $echoarray['company'] = $row['Agency'], $echoarray['desc'] = $row['Notes'], $echoarray['age'] = $row['Date_Birth'], $echoarray['title'] = $row['Occupation'], $echoarray['phone'] = $row['Phone'], $echoarray['email'] = $row['Email'], $echoarray['zip'] = $row['Phys_Zip'], $echoarray['country'] = $row['Phys_City'] ); } Any Ideas? hello freaks,
I have a four-element array, which is the result of a mysql query. The array is like below. (This is of course just a snippet to show the structure; the hours of course go up to 24, then repeat; there are about ten days' worth of data.)
Array ( [dayname] => day1 [hour] => 1 [widtype] => type1 [Output] => 20 ) Array ( [dayname] => day1 [hour] => 2 [widtype] => type1 [Output] => 9 ) Array ( [dayname] => day1 [hour] => 1 [widtype] => type2 [Output] => 450 ) Array ( [dayname] => day1 [hour] => 2 [widtype] => type2 [Output] => 650 ) I want to loop through this data and output each hour's data in a separate line, like below (I included the headings just for clarity): Day Hour Type1_total Type2_total day1 1 20 450 day1 2 9 650 ... and can't seem to make this happen. Here's the code I've written: $prevday = ''; while ( $row = mysql_fetch_assoc($result)) { extract($row); $currentday = $row['dayname']; $currenthour = $row['hour']; $currentwid = $row['widtype']; while($currentday !== $prevday){ for($currenthour = 1; $currenthour <=24; $currenthour++){ if($row['widtype'] == 'type1'){ $type1_total = $row['Output'];} if($row['fuel'] == 'type2'){$type2_total = $row['Output'];} print "<pre>"; echo "$currentday, $currenthour, $type1_total, $type2_total"; print "</pre>"; } $prevday = $currentday; } }... and here's what it outputs: day1, 1, 20, , day1, 2, 20, , Clearly I have written this loop wrong but have banged my head against it for a while and wonder if it's just not possible to do what I want. Any suggestions would be hugely appreciated! I have been trying to solve this problem for a few days now and can't seem to work it out. I'm sure i'm missing some simple point.. I am using a mysql PDO fetch to return 2 fields in each row and then put them into an array of their own: foreach ($st->fetchAll() as $row){ $subs[] = array($row['subscriber'],$row['plant']); Some of the rows share the same $row[0], which is the 'subscriber' field. What I want to do is make up another array with each smaller array having a single, unique $row[0] and any number of added 'plant' fields following (e.g $row[1],$row[2] etc). I've tried all sorts of ways to achieve this but am at a loss. Would someone be able to point me in the right direction ? Thanks. I am trying to store all the elements of my tree in an array.My code produces multi dimensional array, but i want it to be one dimensional. How can i get it ? Code:- Code: [Select] function tree_gather($node) //Function to calculate count { $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']; $child[] = tree_gather($array['lchild']); $child[] = tree_gather($array['rchild']); } return $child; } Result:- Code: [Select] Array ( [0] => 2 [1] => 3 [2] => Array ( [0] => 4 [1] => 5 [2] => Array ( [0] => 10 [1] => 11 [2] => [3] => ) [3] => Array ( [0] => 8 [1] => 9 [2] => [3] => ) ) [3] => Array ( [0] => 7 [1] => 6 [2] => Array ( [0] => 15 [1] => 14 [2] => Array ( [0] => 16 [1] => 17 [2] => [3] => ) [3] => ) [3] => Array ( [0] => 13 [1] => 12 [2] => [3] => ) ) ) Table: - I'm not entirely sure how to phrase the title, so I hope it's appropriate... I have an array which looks like the following.. Code: [Select] Array ( [contact] => Array ( [0] => Array ( [name] => Someone Cool [number] => 1234567890 ) ) [messages] => Array ( [0] => Array ( [message] => A message that was recieved [date] => 1234567890 [type] => 1 ) [1] => Array ( [message] => A message which was sent [date] => 1322175702616 [type] => 2 ) ) [calls] => Array ( [0] => Array ( [datetime] => 1320674980836 [type] => 1 [duration] => 7 [number] => 1234567890 ) [1] => Array ( [datetime] => 1320675327541 [type] => 2 [duration] => 638 [number] => 1234567890 ) ) ) [messages] can have anywhere between 40 and 3000 children [calls] can have anywhere from 0 to 200ish children ** These are generals, but realistically, either can have any number. What I'm trying to do is dump all messages and calls. The catch is this: When dumping a call, a check needs to be run against datestamps and only dump the next call coming out where the datestamp of the call is NEWER than the LAST message dumped, AND OLDER than the message that is to be dump in this cycle of the loop. What I have so far is the following... Code: [Select] foreach($vardump['messages'] as $message) { // So we have a reference point for the first call we're going to dump if(!is_numeric($last_message_stamp)) { $last_message_stamp = $message['date']; } if( trim($vardump['calls'][$calls_counter]['datetime']) > trim($last_message_stamp) && trim($vardump['calls'][$calls_counter]['datetime']) < trim($message['date'])) { // Dump the calls row! echo(" <div class=\"chatbubble-call\"> <div class=\"chatbubble-person\">".$vardump['contact'][0]['name']."</div> <p>".$vardump['calls'][$calls_counter]['number']."</p> <p>".date("h:i:s", $vardump['calls'][$calls_counter]['number'])."</p> <div class=\"chatbubble-datetime\">".date("l, j F, Y -- h:i:s", $vardump['calls'][$calls_counter]['datetime'] / 1000)."</div> </div> "); // Increase our calls index $calls_counter++; } // Begin dumping Texts out :D // Let's see which style type we're dumping out... if($message['type'] == 2) { // Message Sent echo(" <div class=\"chatbubble-sent\"> <div class=\"chatbubble-person\">Pat Litke</div> <p>".$message['message']."</p> <div class=\"chatbubble-datetime\">".date("l, j F, Y -- h:i:s", $message['date'] / 1000)."</div> </div> "); } else { // Message Recieved echo(" <div class=\"chatbubble-recieved\"> <div class=\"chatbubble-person\">".$vardump['contact'][0]['name']."</div> <p>".$message['message']."</p> <div class=\"chatbubble-datetime\">".date("l, j F, Y -- h:i:s", $message['date'] / 1000)."</div> </div> "); } // Reset our $last_messge_stamp variable $last_message_stamp = $message['date']; } I should also add that I am using the following queries to pull this date out of my database... Code: [Select] $sql_get_messages = "SELECT * FROM messages WHERE thread_number LIKE '%$the_thread%' ORDER BY epoch_date ASC"; $sql_get_calls = "SELECT * FROM calls WHERE number LIKE '%$the_thread%' ORDER BY datetime ASC"; $sql_get_contact = "SELECT * FROM contacts WHERE number LIKE '%$the_thread%' LIMIT 1"; But, I feel that this is horribly inefficient, and it doesn't work right... I only ever get a single call dumped. What am I doing wrong? The code below is showing "undefined" and "OBJECT" errors
What am I doing wrong to build this multi-dimensional array?
And why can't I paste it to this page???????????????????????
I have four different arrays and I want to place them into a multi dimensional array and then I want to place it into a Session variable. This is what I have below.How do I do this? when I print_r($_Session) I don't get anything just option[](2); Code: [Select] $_SESSION ['option']['green'] = array('name '=>'jeff'); $_SESSION ['option']['red'] = array('name '=>'mary'); $_SESSION ['option']['blue'] = array('name '=>'joe'); $_SESSION ['option']['brown'] = array('name '=>'ash'); Hi guys, I'm still stuck on making this multi-level drop down menu, so I figure that I'll listen to how you guys would do it. I don't necessarily need any code, but just ideas on how to code it. Basically, I need it to store each item in a database. It needs to: be accessed, processed, and formatted with PHP end up returning either a multi-dimensional array, or the raw HTML. Examples: Code: [Select] <?php array( array( 'label'=>'Test', 'link'=>'index.php?r=test', 'sort'=>0, 'children'=>array(--blah blah blah--) ), array(--blah blah blah--) ); Code: [Select] <div id="menu"> <ul> <li><a href="index.php?r=test"><h2>Test</h2></a> <ul> <li><a href="blah">Blah</a> <ul> <li><a href="blah">Blah</a></li> </ul> </li> </ul> </li> </ul> </div> That's pretty much it. If you have any ideas or suggestions, please feel free to help me out. Thank you guys! Hi - I have an array which is created from a session variable I must have constructed my array wrong, as for the life of me I can not extract the individual values. I have tried innumerable $key=>$value combinations. I must be doing something stupid, maybe it is obvious, but not to me. I'll be darn grateful if you can help me ! Many Thanks MY array looks like this: Code: [Select] Array ( [quantity] => Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 1 [4] => 1 ) [name] => Array ( [0] => Ribs Large pack 20 pieces [1] => 25 Piece Bag [2] => Sirloin Steak [3] => 50 piece bag of Scalops [4] => Sirloin Steak ) [prodid] => Array ( [0] => 17 [1] => 28 [2] => 27 [3] => 25 [4] => 27 ) ) The CodeIgniter form which generated this array looks like this: Code: [Select] <?php foreach ( $_SESSION['openorders'] as $key=>$value) { ?> <tr align="center"> <td width="30"><?php $data=array('name' =>'quantity[]','value'=>$value['quantity']); echo form_input($data); ?></td> <td><?php echo $value['prodid']; ?></td> <td><?php echo $value['name'];?></td> <td><?php echo $value['ordervalue']; ?></td> <td><?php echo $value['pricelb']; ?></td> <td align="right"><?php echo form_checkbox('delete','delete',FALSE); echo form_hidden('prodid[]', $value['prodid']); echo form_hidden('name[]', $value['name']); echo form_hidden('orderid', $value['orderid']); $totalordervalue += $value['ordervalue']; } ?> I have an Array and I am attempting to figure out how I can sort it by date. Example of Said Array: Code: [Select] Array ( [0] => Array ( [userComments0] => Array ( [bodyType] => 0 [created] => 2011-02-01 23:51:43 [currentUserFromGroup] => MEMBER_ONE [body] => We should all wear wooden clogs on Fridays. Who's with me? Huh? Anyone? ) ) [1] => Array ( [userComments1] => Array ( [bodyType] => 0 [created] => 2011-02-09 18:20:51 [currentUserFromGroup] => MEMBER_ONE [body] => Test ) ) [2] => Array ( [userComments2] => Array ( [bodyType] => 0 [created] => 2011-02-11 21:02:23 [currentUserFromGroup] => MEMBER_ONE [body] => TEst ) ) [3] => Array ( [userComments3] => Array ( [bodyType] => 0 [created] => 2011-02-12 17:02:31 [currentUserFromGroup] => MEMBER_ONE [body] => Posting a new idea ) ) [4] => Array ( [userComments4] => Array ( [bodyType] => 0 [created] => 2011-02-13 23:32:19 [currentUserFromGroup] => MEMBER_ONE [body] => Test Idea ) ) [5] => Array ( [userComments5] => Array ( [bodyType] => 0 [created] => 2011-02-10 01:50:34 [currentUserFromGroup] => MEMBER_TWO [body] => Taco sauce is as good as French Toast! ) ) [6] => Array ( [userComments6] => Array ( [bodyType] => 0 [created] => 2011-02-10 01:51:03 [currentUserFromGroup] => MEMBER_TWO [body] => Need to hire more engineers! ) ) [7] => Array ( [userComments7] => Array ( [bodyType] => 0 [created] => 2011-02-10 01:51:42 [currentUserFromGroup] => MEMBER_TWO [body] => Golden Bears are all washed up ) ) [8] => Array ( [userComments8] => Array ( [bodyType] => 0 [created] => 2011-02-12 00:13:14 [currentUserFromGroup] => MEMBER_TWO [body] => The JETS are going to kick ass! ) ) [9] => Array ( [userComments9] => Array ( [bodyType] => 0 [created] => 2011-02-14 02:23:47 [currentUserFromGroup] => MEMBER_TWO [body] => We are getting there! ) ) ) But I have stumped myself on it, and cant wrap my mind around getting it sorted by datetime. I don't know where I should begin on this one fellas. I am validating a form, and if there are errors in the input, the error array is filled with appropriate mssg and the "sticky" form with right values is shown back, and errors on top. Example: first name, last name, email, date of birth. each field is validated,and if for example first name does not pass,i will nullify the value and populate error array like below: $_SESSSION['error']['fname']="Please check the format of the name,can contain only alphabets!" $_SESSSION['error']['email']="Please check the format of email!" When I slap back the form, last name has passed, and so will have the previously entered value, but first name and email will be empty, and i need to know how to display the 2 errors on top of the form. It uses post method, and posts to itself. Hey everyone. I'm in the final stage of my thingeee (yay). The last thing I need is to prepare a report, but I'm slightly lost on how to do it. Essentially, I have a query that returns some financial records and need to aggregate the data manually (in PHP). I'm familiar with the foreach($assoc_array as $array) function, and I'd like to use it to manipulate the output as follows: For the first key (instType), this will mark the start of a new table element For a second key (paymentID), this will mark the start of a new table row element For a third key, (instrumentID), this will mark a new column (<td>) Then, I need to sort by two other keys - deptID, userID, accountID How do I accomplish this? Pseudo-code is acceptable (my array is called $data and contains all the keys I listed above) Does anyone know of a way I can natsort a multi-dimension array by a value nested in the array 2 keys deep? I.e. array( 'test1' => array( 'location' => '123 fake street', 'time' => 120 ), 'test2' => array( 'location' => '123 elm street', 'time' => 34 ), 'test3' => array( 'location' => '123 php street', 'time' => 133 ) ); // would become array( 'test2' => array( 'location' => '123 elm street', 'time' => 34 ), 'test1' => array( 'location' => '123 fake street', 'time' => 120 ), 'test3' => array( 'location' => '123 php street', 'time' => 133 ) ); thanks for any help I have an array which will be below. The array is being built from an XML file, the problem is I need to extrapolate data from it.
I am having trouble with looping through the array properly.
The output should be something like this:
Beth's state is 0 (Where Beth's is the name and 0 is the state)
Clint's state is 0
Array ( [0] => Array ( [did] => 216616014153767704 [known] => 1 [lock] => 0 [state] => 0 [level] => 100 [node] => 30 [port] => 0 [nodetype] => 16386 [name] => Beth's [desc] => LED [colorid] => 1 [type] => multilevel [rangemin] => 0 [rangemax] => 99 [power] => 0 [poweravg] => 0 [energy] => 0 [score] => 0 [productid] => 1 [prodbrand] => TCP [prodmodel] => LED A19 11W [prodtype] => LED [prodtypeid] => 78 [classid] => 2 [class] => [subclassid] => 1 [subclass] => [other] => ) [1] => Array ( [did] => 216616014154116936 [known] => 1 [lock] => 0 [state] => 0 [level] => 100 [node] => 30 [port] => 0 [nodetype] => 16386 [name] => Clint's [desc] => LED [colorid] => 1 [type] => multilevel [rangemin] => 0 [rangemax] => 99 [power] => 0 [poweravg] => 0 [energy] => 0 [score] => 0 [productid] => 1 [prodbrand] => TCP [prodmodel] => LED A19 11W [prodtype] => LED [prodtypeid] => 78 [classid] => 2 [class] => [subclassid] => 1 [subclass] => [other] => ) ) |