PHP - Recursive Iteration
Hello,
Here is my code:
<?php require 'vendor/autoload.php'; $client = new Elasticsearch/Client(); $root = realpath('~/elkdata/for_elk_test_2014_11_24/Agencies'); $iter = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD); $paths = array($root); foreach ($iter as $path => $dir) { if ($dir -> isDir()) { $paths[] = $path; } } //Create the index and mappings $mapping['index'] = 'rvuehistoricaldocuments2009-2013'; //mapping code $mapping['body'] = array ( 'mappings' => array ( 'documents' => array ( '_source' => array ( 'enabled' => true ), 'properties' => array( 'doc_name' => array( 'type' => 'string', 'analyzer' => 'standard' ), 'description' => array( 'type' => 'string' ) ) ) ) ); $client ->indices()->create($mapping) //Now index the documents for ($i = 0; $i <= count($paths); $i++) { $params ['body'][] = array( 'index' => array( 'type' => 'documents' 'body' => array( 'foo' => 'bar' //Document body goes here ) ) ); //Every 1000 documents stop and send the bulk request. if($1 % 1000) { $responses = $client->bulk($params); // erase the old bulk request $params = array(); // unset the bulk response when you are done to save memory unset($responses); } } ?>I am looking to index a large amount of documents using elastic search and php. I have a very complex directory filled with other directories that i need to index into an array. I wanted to see if my code looked right, and if not what am I doing wrong? Thanks, Austin Harmon Similar Tutorialshi I'm coding a page and I was trying to iterate an iteration. but it doesn't seem to work. is this possible in php? Code: [Select] $pageTpl->setIteration('iPlaylist'); // loop all collections and output them foreach ($playlists as $playlist) { // assign collection & urls in template $pageTpl->assignIteration('playlist', $playlist['Title']); $pageTpl->refillIteration(); $pageTpl->setIteration('iMusic'); foreach ($songs as $song){ $pageTpl->assignIteration('path', STREAMING_PREFIX.substr($song['Filename'], 7)); $pageTpl->assignIteration('songId', $song['SongId']); $pageTpl->assignIteration('title', $song['Title']); $pageTpl->assignIteration('artist', $song['Artist']); $pageTpl->assignIteration('time', FYMFunctions::Sec2hms($song['Length'])); $pageTpl->assignIteration('genre', $song['Genre']); $pageTpl->assignIteration('delete', 'removeSong('.$song['SongId'].')'); $pageTpl->refillIteration('iMusic'); } // parseIteration $pageTpl->parseIteration('iMusic'); } // refillIteration $pageTpl->refillIteration(); // parseIteration $pageTpl->parseIteration('iPlaylist'); this is the piece of code... did I do anything wrong? To solve a bigger issue I'm having in WordPress, I have thrown together this basic script in PHP script to help me get to the bottom of it. Basically, I am trying to add a <hr /> tag after every 3rd paragraph: http://www.mattpealing-server.co.uk/~freshmat/wp-content/themes/match2move/test.php With the following code: <?php $count = 0; ?><?php while($count < 20) : ?><span><p><strong><?php echo $count; ?>:</strong> Lorem ipsum dolor sit amet, consectetuer adipiscing.</p></span><?php if ($count % 3) : ?><hr /><?php endif; ?><?php $count ++; ?><?php endwhile; ?>() However if you notice, this output just doesn't turn out like this! Does the operator I'm using not test if $count is a multiple of 3? Hello, I have two classes: Code: [Select] abstract class Serializable { public function serialize() { foreach($this as $member => $value) { $publicObject->$member = $value; } return $publicObject } } class ToSerialize extends Serializable { public function otherSerialize() { foreach($this as $member => $value) { $publicObject->$member = $value; } return $publicObject } } $foo = new ToSerialize(); $foo->serialize(); //This will return one thing $foo->otherSerialize(); //This will return something different Why does this happen? So I have a very simple for loop that I am populating a list with levels and exp required to achieve the next level. I have been using a sandbox to test my output and have also created an excel sheet to replicate the data to verify the content. This code was not mine from the beginning and in creating the spreadsheet I discovered the flaw. Below is the code I am trying to fix: function experience($L, $pres = 0) { $a = 0; $end = 0; for ($x = 1; $x < $L; ++$x) { $a += $x * round($x + 5 * pow(4, ($x / 300))); } if ($x > 199) { $a += $x * round($x + 7 * pow(4, ($x / 290))); } if ($x > 399) { $a += $x * round($x + 11 * pow(4, ($x / 280))); } if ($x > 599) { $a += $x * round($x + 19 * pow(4, ($x / 270))); } if ($x > 799) { $a += $x * round($x + 35 * pow(4, ($x / 260))); } if ($x > 999) { $a += $x * round($x + 67 * pow(4, ($x / 250))); } return round($a / 1.25); } Below is the troubleshooting I am attempting to do (Modified and simplified for and while loop): //for loop $no = 200; $a = 0; for ($x = 1; $x < $no; ++$x) { $a += $x + 1; } if ($no > 199) { $a += $x + 2; } echo $a; //while loop $no = 200; $a = 0; $x = 1; while (($x - 1) < $no) { $a += $x * round($x + 5 * pow(4, ($x / 300))); $x++; if ($x > 199) { $a += $x * round($x + 7 * pow(4, ($x / 290))); } } echo $a; Upon request I can also provide snipets of the excel sheet. So the gist of what the issue I am having is this. Between level 199 and 200 the iteration of the loop is running one extra time through the initial formula. As you can tell at level 200, 400, 600, 800 and 1000 I want this formula to change so that it simplifies the amount of exp required to achieve the next level. I can not for the life of me figure out how to restrict the loop while still allowing the values 200 up to run through it for the first 199 iterations. The output I should get from the primary code for levels 199 through 201 are as follows: 199 = 200 = 201 = At level 199 I am good but for whatever reason it runs one additional iteration at the level 1-199 formula and then moves on to the 200 level formula messing up the values. Any and all help is much appreciated. I am a novice hobbyist at best and have been doing this for many, many years now but sometimes I get stumped. I chalk it up to lack of proper training and time to really be serious with it. Thanks in advance....NICON Specific question with general application here. i am having some trouble with a loop and am getting some odd timing results specifically this is a WMI query on a hyper-v server retrieving disk information but im not sure the context of the query is relevant here. The main question is how come the first iteration of the loop is so much slower than the other iterations, it just doesnt seem to make sense to me unless ive done something stupid here i cannot see. any ideas ? Code: [Select] <?php $diskstart = microtime(true); // get the hard disk size try { $resultDisk = $wmi->ExecQuery("SELECT BlockSize,NumberOfBlocks FROM msvm_LogicalDisk where systemname like '%" . $guid . "%' and name='Hard Disk Image'"); $ct=0; $start1 = microtime(true); $start = microtime(true); foreach($resultDisk as $itemDisk) { $end = microtime(true); echo "<BR>FOREACH: [" . Round($end-$start,3) . "] seconds"; $vm[$name]['disks'][$ct] = ($itemDisk->BlockSize * $itemDisk->NumberOfBlocks)/1024; // format the disk size into KB $ct++; $start = microtime(true); } $end1 = microtime(true); echo "<br> ALLLOOP: [" . Round($end1-$start1,3) . "] "; } catch(exception $e) { } $diskend = microtime(true); echo "<br>DISK: [" . ($diskend-$diskstart) . "] seconds"; ?> and here are the results Code: [Select] FOREACH: [1.236] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.002] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds ALLLOOP: [2] DISK: [2.1837468147278] seconds 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? Evening everyone and Merry X-Mas (Happy Holidays) or whatever fits you best.... I have been trying over and over for about 12 hours to figure out how to get data from a specific JSON response and assign the specific values to a new array key/value pair. The various ways I have tried to figure this out are numerous so i'm going to avoid the runnig list of "I trieid this...and this...and this... etc etc." just understand I have reached a dead end point where I need help badly.
Here is what our end goal is:
"The company" is a "service industry" provider (plumbing, electrical etc. etc.) who wants to dispatch its technicians to new jobs based on which technician has the shortest travel time from any existing address where they already have a scheduled appointment that day and has available time in there schedule. Thus the dispatching system when a new service call is entered is going to give "recommended" technicians (up to 4) to be assigned the new service call based on the above mentioned criteria. (Efficient routing to save company gas cost)
1.) We have a "New service" street address assigned to the $to variable: $to = "4813 River Basin Dr S, Jacksonville FL 32207"; 2.) We will have "records" array which containes a series of records, each record consists of a ticket# a technician id# and a street address: $records = array( array("DV1012","30453423","9890 Hutchinson Park Dr Jacksonville, FL 32225"), array("DB3434","30404041","821 Orange Ave Crescent City, FL 32112"), array("DB3434","30605060","1972 Wells Road, Orange Park FL 32073"), array("DB4578","30605060","2 Independent Drive, Jacksonville FL 32202"), array("DB7841","30605060","5000 Norwood Avenue, Jacksonville FL 32208"), array("DB3235","30605060","9501 Arlington Expressway, Jacksonville FL 32225"), array("DB7894","30605060","Massey Avenue, Jacksonville, FL 32227"), array("DB2020","30121212","11200 Central Pkwy Jacksonville, FL 32224") ); 3.) We are going to prepare the records array for submission to Google's Distance Matrix API by URL encoding each array value into a single variable and then submit it: foreach ($records as $key => $value) {$from = $from.urlencode($value[2])."|";} $to = urlencode($to); $data = file_get_contents("//maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&units=imperial&mode=driving&sensor=false"); $res=json_decode($data) or die("Error: Cannot read object"); You may look at the ACTUAL live Google response from this he http://tiny.cc/i6eerx (We have applied <pre> and var_dump($res) to the output) We are looking to get the following information back: The distance and travel time between the "New Service" address ($to) and each of the address' in the $records array ($from), now once that information is returned from Google (JSON response) we need to parse the response and narrow it down to 4 or less (Based on the 4 lowest drive times) to form a new array which ends like this: $results = array( array("DV1012","30453423","2.3 Miles","8 mins"), array("DB3434","30404041","2.8 Miles","9 mins"), array("DB3434","30605060","4.6 Miles","13.8 mins"), array("DB4578","30605060","5.7 Miles","15.2 min") ); OUR PROBLEM: Everything up until the the Google API response is fine, but iterating over the multidimensional arrays within multidimensional arrays of the JSON response is just not coming together in my head (or 2 dozen code attempts). I am able to ECHO an individual value like ( echo $res->rows[0]->elements[0]->distance->text; ) but this has no value for the end result i need to get to. My last thoughts and efforts was that that I was going to have to embed foreach statements within foreach statements to drill down through the various arrays but that hasn't worked very well and it seems like it shouldn't be how it has to be done. I would appreciate any help in showing me how the iteration code should be written and any explanation about the code so i can wrap my head around it. I have an array of property details that prints to the page. Later on that same page, I would like to use one of the array's values as part of a mailto script, but I can't seem to figure out how to recall it. could someone point me in the direction of how I can make the array's values available for later use? I hope this is clear enough. Thanks I am doing some study on using time() and date() and i just wrote this simple for loop to add one day to each iteration with +$i and its echoing the unix timestamp as opposed to the correctly formated date as it should be based on my code. Anyone have any idea why this is not working as expected? for($i=0; $i < 50; $i++) { echo $time = time()+$i . "<br />"; // add a day on each iteration echo date('y-m-d', $time) . "<br />"; // should echo 10-12-02, 10-12-03, 10-12-04, etc.. } what am i doing wrong here? arrgggg! maybe its too late for this s$%^#!
$start = 0; Something bothers me: I am writing a PHP code to implement "step by step" form. In order to do that, I copied a method which looks like: Program name: doit.php : if (!isset($_SESSION['para_stage'])) { ... first time to the code .... initialize variables ...display first form which calls doit.php when submit.....} else {already been to this code, variables are initialized, do what you have to do and recall doit.php ....} It works fine, but: isn't there a problem with calling the same program again and again from itself? isn;t it like a recursive, which means the stack will be used until overflow? I'm really fond of your coding and need some help too I'm also trying to make a tree and save it in an xml file such that parent_id of one node is inserted in as pages key to the father node.By running this query $sql = "Select * from category order by parent_id ASC"; I'm getting the following result. Array ( => Array ( [category_id] => 2 [parent_id] => 0 [category_name] => Clothes ) [1] => Array ( [category_id] => 5 [parent_id] => 1 [category_name] => T-shirts ) [2] => Array ( [category_id] => 6 [parent_id] => 1 [category_name] => Cotton-Shirts ) [3] => Array ( [category_id] => 1 [parent_id] => 2 [category_name] => Upper ) [4] => Array ( [category_id] => 4 [parent_id] => 2 [category_name] => Lower ) [5] => Array ( [category_id] => 3 [parent_id] => 4 [category_name] => Pants ) ) My code is as follows but not executing correctly function searchTree($arr,$node,$i){ if(!in_array($node['parent_id'],$arr[$i])) { $stmt = '<pages_'.$i.'>'; $stmt .=$node; $stmt .='</pages_'.$i.'>'; return $stmt;} else{ //print_r($returnTree); print_r ($arr[$i]);//['category_id']; $returnTree = ($arr[$i]['category_id']==$node['parent_id'])? searchTree($arr,$node,$i++): searchTree($arr,'',$i++); } } $i=0; foreach($links as $link){ $myArr = searchTree($links,$link,$i);} The result should be as follows: <page_1> <label>Clothes</label> <uri>#</uri> <pages> <page_1_1> <label>Upper</label> <uri>#</uri> <pages> <label>T-Shirt</label> <uri>#</uri> <page_1_1> <page_1_1_1> <label>Short Sleaves</label> <uri>#</uri> </page_1_1_1> <page_1_1_2><label>Long Sleaves</label><uri>#</uri> </page_1_1_2></page_1_1></page_1> <page_1_2> <label>Lower</label> <uri>#</uri> <pages>....</page_1_2> Hopefully you can unsderstand this problem. Please help me. Code: [Select] public function getBonusChildren($userID) { if($userID != NULL) { $sql = 'SELECT COUNT(*) AS count, userID FROM jos_backoffice_users WHERE parentID= ' . $userID . ';'; $stmt = conn::getInstance()->prepare($sql); $stmt->execute(); $obj = $stmt->fetchAll(PDO::FETCH_ASSOC); if(is_object($obj)) { $obj->count += $this->getBonusChildren($obj->userID); } } return $obj->count; } I get no error. It just always return null. How can I get this done? Hello! Maybe I'm a bit ashamed to question some little kind of thing, but I tested 3 hours and couldn't let this function. It's like the most easiest possible recursiv function...: Code: [Select] function recursiv($s){ $s.="b"; if(strlen($s)>30){return $s;} //else return 0; else recursiv($s); } echo recursiv("h"); The result is a blank page... Thanks a lot for your help !! Hi there, I have written a recursive function that basically generates a tree structure for my site pages (kind of like a sitemap). It all worked fine until yesterday, I started getting error messages telling me that I have exhausted the amount of memory available. There are only about 30 pages in the site (parent, child, sub-child etc), so I dont think that I should be using up that much memory. This was my first attempt at a recursive function so I am pretty sure that it may not have been optimised properly. If anyone could take a look and offer any feed back that would be great. (written in codeigniter framework) function getAllPages() { $this->tmp_arr = array(); $this->buildPageStructure(0, 0); return $this->tmp_arr; } function buildPageStructure($parent_id, $counter) { $CI = & get_instance(); $query = $CI->db->query("SELECT page_id, title, page_url, status FROM pages WHERE parent_page='$parent_id' ORDER BY sort_order ASC"); $counter++; if($query->num_rows() > 0) { foreach($query->result() as $row) { $new_arr = new Page(); $new_arr->page_id = $row->page_id; $new_arr->title = $row->title; $new_arr->level = $counter; $new_arr->page_url = $row->page_url; $new_arr->status = $row->status; $this->tmp_arr[] = $new_arr; $this->buildPageStructure($row->page_id, $counter); } } } Cheers Jon Hey guys, I've got a problem. I need a function, that gives me a menue like that: parent_page1 page1 page2 page3 parent_page2 page1 page2 page3 So.. here is my database structu All what I need, is a function, that gives me a menu like that on top. Do you need some more information? Let me know.. I have a function that searches first for a line in a file and then for a string in that line. If the string is not found, it concatenates the line with the next line and so on until it finds the string. The following script works but it is time consuming. I want to put a "break" somewhere so that if the line is found, the foreach will break. Can someone please help and tell me how to do this? If I put the break before the recursive call, it wont do the call. If I put it after, it wont get to the break. Thanks! function findEndTag($file, $line, $consolidatedLine) { $endTagFound = strstr($consolidatedLine,"/>"); if (!$endTagFound) { $fileContent = file($file); foreach ($fileContent as $i => $lineArray) { if ($lineArray == $line) { $consolidatedLine = $consolidatedLine." ".$fileContent[$i+1]; return (findEndTag($file, $fileContent[$i+1], $consolidatedLine)); } } } else { return $consolidatedLine; } } If i have a list of categories like: 1. Billboards and advertisement section 1(a)City Clock 1(a)(i)Application fee (has columns for approved price and proposed price) 1(a)(ii)Advertisement Per year (has columns for approved price and proposed price) 1(b)Billboards 1(b)(i)Application fee for construction (has columns for approved price and proposed price) 1(b)(ii)Charge per year without advertisement (has columns for approved price and proposed price) 1(c)Something here..... 1(c)(i) something here...(has columns for approved price and proposed price) 1(c)(ii)something here...(has columns for approved price and proposed price) 1(c)(iii) something here... (has columns for approved price and proposed price) e.t.c THEN SOME CATEGORIES LOOK LIKE:category 2 2. Category name 2(a)something here..(has columns for approved price and proposed price) 2(b)something here.. 2(b)(i)something here..(has columns for approved price and proposed price) 2(b)(ii)something here..(has columns for approved price and proposed price) NOW: i have categories without sub categories and others with sub-sub categories , a main category doesn't does have a column for prices ( or lets just say other columns) , a sub category WITHOUT its sub category will have columns for prices, if a sub category has its sub category, then its subcategory should have columns for prices (this is where my problem is - how do i handle such a situation in php Mysql?? ) i have the below script but it doesn't work it just refreshes the page anyone know what is wrong Code: [Select] <?php $path = "../../gallery/gallery_files/gallery/"; if(isset($_POST['file']) && is_array($_POST['file'])) { foreach($_POST['file'] as $file) { $dirname = $path; //Recursive Delete Function function DELETE_RECURSIVE_DIRS($dirname) { // recursive function to delete // all subdirectories and contents: if(is_dir($dirname))$dir_handle=opendir($dirname); while($file=readdir($dir_handle)) { if($file!="." && $file!="..") { if(!is_dir($dirname."/".$file))unlink ($dirname."/".$file); else DELETE_RECURSIVE_DIRS($dirname."/".$file); } } closedir($dir_handle); rmdir($dirname); return true; } } } ?> Dear all, Hello, i'm a newbie programmer. I want to implement the concept about recursive descent parser for natural language (english). The concept was found in http://nltk.sourceforge.net/doc/en/ch07.html#rdparser. But my problem is, how to implementation the concept/theory to PHP code ? Anyone would to help me to give the advice or tutorial or maybe anyone has to make script before? Thank you very much in advance. |