PHP - Need Help Accessing Array Variable After Iteration
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 Similar TutorialsI use a CURL script API with the header "$headers[] = 'Content-Type: application/json';" The script ends with "$result = curl_exec($ch);" If I simply echo the $result to my browser, I get an array that looks like this:
stdClass Object
[toAddress] => stdClass Object Do I really need to "json_decode" this array? I've spent 2 1/2 days trying every which way, with every permutation to access that one value:
echo $result["fromAddress"]["phone"]; Unfortunately I must have fallen asleep during the array lesson in PHP class ? Thank you. 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? I have the following code in zend: Code: [Select] $arrErrors=array(); if (!empty($this->post['submit'])) { // Each time theres an error, add an error message to the error array // using the field name as the key. if (empty($this->post['client_name'])) $arrErrors['client_name'] = "Please Enter Client's name as it appears in the carrier software"; } if i set $this->view->arrErrors=$arrErrors in the controller, Can I access it as $this->arrErrors['client_name'] in the view? I have a database query set up that returns an array. I then cycle through the rows in a foreach statement that wraps each value in a <td> tag to output it to a table. It works really great, but now I need to access two of the values and add some info to them. The first field returned is an image filename and I want to wrap it in an image tag that also concatenates the image path location to the value. All the images are stored in the same location, so basically I want to take the first value form the array and add the path to where the images are and wrap the whole thing in an <img> tag. The other field I need to modify is the last value in the array which is actually an email address. For that field I want to make them an active email link so I need to wrap an <a>href=mailto: </a> tag around the value. How could I modify this code so I could add the necessary tags to these elements of the array? Here is the code I am running: Code: [Select] $query = "Select member_image as 'Image', member_name as 'Name', city as 'City', phone as 'Phone', email as 'Email' FROM directory"; //connect to database $conn=db_connect(); //call function do_query to run the query and output the table do_query($conn, $querey); The functions called are as follows: Code: [Select] function db_connect() { $conn = new mysqli("localhost", "username", "password", "databasename"); } function do_query($conn, $query); { $result = mysqli_query($conn, $query); WHILE ($row = mysqli_fetch_assoc($result)) { If (!$heading) //only do if header row hasn't been output yet { $heading = TRUE; //so we only do it once echo "<table>\n<tr<>\n"; foreach ($row as $key => $val) { echo "<th>$key</th>"; } echo "</tr>\n"; } echo "<tr>"; foreach ($row as $val) { echo "<td> $val </td>"; } echo "</tr>\n"; } //close the while echo "</table>\n"; } 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 I thought I was a beginner PHPer but now I'm not even sure I'm that. I have this class here which starts with: Code: [Select] private static $FormatType = ""; but then further down: Code: [Select] public function SetFormatType($NewFormatTypeId) { $this->FormatType = $NewFormatTypeId; } public function GetFormatType() { return $this->FormatType; } Do you suppose that the original developer just had a singleton or something, then latter on he found that he was making more instances and PHP tolerates this behavior? Or am I missing something? Hi guys im in the middle of optimizing code.. Code: [Select] $sql = "SELECT * FROM sa_enemystats WHERE username='$username'"; $res = mysql_query($sql); while ($row = mysql_fetch_assoc($res)) { $enemy['current_health'] = $row['current_health']; $enemy['current_skill'] = $row['current_skill']; $enemy['level'] = $row['level']; $enemy['damage'] = $row['damage']; $enemy['evade'] = $row['evade']; $enemy['accuracy'] = $row['accuracy']; $enemy['speed'] = $row['speed']; $enemy['luck'] = $row['luck']; echo 'debug: variables synced with db table'; }I know that the setting of these variables are messy and can be done in a better way... but how? I have tried foreach and copying other's code for an array copy but it lead no where. Then again my syntax could be wrong... I used something like Code: [Select] foreach ( $enemy[$value] as $row => $value) { $enemy[$value] = $row[$value]; } I need a help in the following : I have an admin page from where the admin attaches an gif image.This attached image should be shown to the user as a scrolling image. The code for the scrolling image is done through javascript. So my actual problem is getting the name of the attached gif image to the javascript array which is used for scrolling horizontally. hi 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? hi all, I have an language pack for example: languages/en.php: Code: [Select] $en['mail']['letter closing'] = "regards,\n your friend!"; and in my config: Code: [Select] $language = "en"; $include_language = @include("languages/".$language.".php"); if(!($include_language)) { $try_default_language = @include("languages/nl.php"); if(!($try_default_language)) { echo "kan de taalpakket niet vinden<br>"; echo "Could not find the language pack.<br>"; echo "example on error: ".$test." shows nothing"; exit; } } In my function I want to include the language pack for example i have $language = 'en' so I want to include $en['general']['letter closing'] I will do this: Code: [Select] global $language,${$language}['general']; But that gives an error unexpected '[' blah blah. How can i call the variable variable array in the valid php way? 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? 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,
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 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 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 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; Code: [Select] $word = 'numbers'; $numbers= array('1', '2', '3', '4'); echo $$word[0]; I expected the output to be '1'. It ended up being nothing... Why does this not work? Is it not possible to have a variable variable array? And if not, is there a workaround? Cheers, Joe Hey, im struggeling with a small piece of code.... Thats my code: Global $user_ID; $user_ID = get_current_user_id(); echo"User number $user_ID is loggedin";
Echo gives me this:
Now i want to add it to my array: $atts['href'] .= $user_ID . 'abc'; 'href' is set to "https://test.com/" What im getting now ist https://test.com/abc
Can someone tell my why the '2' is missing??
|