PHP - Calling The Last String Of An Array
I want to echo the last two (or at least the last) string of an array. What is the simplest way to do so ?
Similar TutorialsThanks in advance for help. I have a PHP script that has a function called traverseXMLNodes and it passes an xml string. I want anyone with a username and password to be able to call this function from his website or application or programming. In short i want my site to act as an API(Application Programming Interface). I am really stuck as to how to go about this. There are other functions i would like to call as well so traverseXMLNodes is not the only function i want to my "API" users to access. Below is the code I am using. the filename for my php i called remote.php. I am using the following query string to test and no results are returned. http://localhost/testfolder/remote.php?xmlstring=20 Code: [Select] <?php $allowedfuncs = array('xmlstring','remotefunction2'); if(in_array($_get['xmlstring'], $allowedfuncs)) { $func = $_get['xmlstring']; $output = traverseXMLNodes($func); // This calls $_get['funccall']() echo $output; } else { exit(); } function traverseXMLNodes ($func) { echo "The XML string is"; echo "<br/>"; echo $func; echo "<br/>"; } /* More functions go here */ ?> What im trying to do is grab a list of items from http://ffxiv.yg.com/items?f=c=6.2.7 and display it for me in a blank layout like Code: [Select] /item/antelope-sinew-cord?id=10007501 - antelope-sinew-cord - 10007501 /item/carbon-fiber?id=10009304 - carbon-fiber - 10009304 etc etc.. But the code i came up with grabs the data great.. (TOOK ME FOREVER TO FIGURE OUT THE PATTERN ) but i finally managed to get it lol.. anyways the following code is Code: [Select] <?php $page_contents = file_get_contents("http://ffxiv.yg.com/items?f=c=6.2.7"); $pattern = '/\/item\/([a-z,-]+[^gil])\?id\=([0-9,]+)/'; $matches = array(); preg_match_all($pattern, $page_contents, $matches); foreach($matches as $item) { echo $item[0] . " - " . $item[1] . " - " . $item[2] . "<BR>"; } ?> It works but not the way im looking.. it gives me data like so Code: [Select] /item/antelope-sinew?id=10007504 - /item/antelope-sinew-cord?id=10007501 - /item/carbon-fiber?id=10009304 antelope-sinew - antelope-sinew-cord - carbon-fiber 10007504 - 10007501 - 10009304 Thanks for whomever to take a look, and thanks for your responses Hello, I am having some trouble with calling certain array values while a condition equals something. I have called values from a database table into an array: $result = mysql_query("SELECT `TeamID`, `ScoreA`, `ScoreB`,`TeamPlayed`, `RoundNum` FROM `scores` WHERE `CompID` = 4 ORDER BY `RoundNum` ASC") or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { print_r($row); } Code: [Select] Array ( [TeamID] => 3 [ScoreA] => 16 [ScoreB] => 4 [TeamPlayed] => 4 [RoundNum] => 1 ) Array ( [TeamID] => 1 [ScoreA] => 16 [ScoreB] => 1 [TeamPlayed] => 6 [RoundNum] => 1 ) Array ( [TeamID] => 2 [ScoreA] => 16 [ScoreB] => 14 [TeamPlayed] => 5 [RoundNum] => 1 ) Array ( [TeamID] => 4 [ScoreA] => 16 [ScoreB] => 0 [TeamPlayed] => 6 [RoundNum] => 2 ) Array ( [TeamID] => 1 [ScoreA] => 10 [ScoreB] => 16 [TeamPlayed] => 2 [RoundNum] => 2 ) Array ( [TeamID] => 5 [ScoreA] => 14 [ScoreB] => 16 [TeamPlayed] => 3 [RoundNum] => 2 ) From here I want to able to get display certain values while RoundNum = $value So while RoundNum = 1 display the array values of: Code: [Select] TeamID V TeamPlayed ScoreA - ScoreB Hope you can decipher what I am asking, don't think I have worded it very well :S. Thanks for anyhelp! Dear all , i am trying the following : i have a class named ACCOUNT with many properties in .some of these properties are array , it is like this : Code: [Select] class ACCOUNT { PRIVATE $DB_LINK; PRIVATE $COMP; PRIVATE $BRANCH; PRIVATE $CURRENCY; PRIVATE $GL; PRIVATE $CIF; PRIVATE $SL; PRIVATE $EXIST; PRIVATE $STATUS; private $ACCOUNT_NAME=ARRAY("LA"=>'',"LE"=>'',"SA"=>'',"SE"=>''); private $ACCOUNT_BALANCE =ARRAY('FC_YTD','CV_YTD','CV_BAL','YTD_BAL','BLOCKED_CV','BLOCKED_FC'); private $CY_NAME=ARRAY("LA"=>'',"LE"=>'',"SA"=>'',"SE"=>''); private $ACCOUNT_NAME_USR=ARRAY("LA"=>'',"LE"=>'',"SA"=>'',"SE"=>''); private $LEDGER_NAME= ARRAY("LA"=>'',"LE"=>''); i have created the following method to call any property [code] FUNCTION GET_SPECIFEC_ATT($ATT,$LANG) { $ATT=$ATT."['L$LANG']"; ECHO $this->$ATT; } but i am getting the below error : Notice: Undefined property: ACCOUNT::$BRANCH_NAME['LA'] in D:\wamp\www\EBANK\account.class on line 186 if i used this : Code: [Select] echo $this->BRANCH_NAME['LA']; it is working fine . and the method is working fine i can iam trying to call property which is NOT an array. Can you please help me in what iam doing wrong ? Thanks in advance Okay, this is getting on my nerves now, my head is throbbing probably just need a break from it all now. I'm currently getting the following message; Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\xampp\htdocs\duff3\test3.php on line 25 Can anyone figure out and explain why this isn't working for me, I believe I am calling the function correctly and then putting the result into a while loop. Code: [Select] <?php function getPageContent($selectedPage) { $sql = "SELECT * "; $sql .= "FROM tbl_pages "; $sql .= "WHERE tbl_pages.pageCategoryId = ".$selectedPage." "; $sql .= "AND active = 1 "; $sql .= "LIMIT 1"; $result = mysql_query($sql) or die ("Error in page sql query:". $sql); return $pageSet; } ?> Code: [Select] <?php require_once ''.$_SERVER['DOCUMENT_ROOT'].'/duff3/commonResources/dbConnection/dbQueryClass.php'; ?> <?php #FUNCTIONS IS A TEMP FILE UNTIL OO PHP COMES INTO PLAY require_once ("commonResources/includes/functions.php"); # if page isn't set then set it to default. if(isset($_GET["page"])) { $selectedPage = $_GET["page"]; } else { $selectedPage = 1; } #call function to select all page $pageSet = getPageContent($selectedPage); ?> <!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> <title> <?php while ($row = mysql_fetch_array($pageSet)) { # Start while loop echo $row["pageTitle"]; ?> </title> <link rel="shortcut icon" href="commonResources/images/container/favicon.ico" /> <link rel="stylesheet" type="text/css" href="<?php $_SERVER["DOCUMENT_ROOT"] ?>/duff3/commonResources/css/style.css" /> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> <!-- PUT COMMON JAVASCRIPT FILES IN AN INCLUDE 05/05/2011 --> <script type="text/javascript" src="commonResources/javaScript/jQuery.js"></script> <script type="text/javascript" src="commonResources/javaScript/jQueryTest/menu.js"></script> <?php require_once ("".$_SERVER["DOCUMENT_ROOT"]."/duff3/commonResources/includes/tinymce.php"); ?> </head> <body> <div id="viewContainer"><!--OPEN DIV FOR VIEW CONTAINER --> <div id="headerContent"><!--OPEN DIV FOR HEADER CONTENT --> <div class="logoContent"><!--OPEN DIV FOR LOGO CONTAINER --> <a href="index.html"><img src="<?php $_SERVER["DOCUMENT_ROOT"] ?>/duff3/commonResources/images/container/logo.png" alt="Hannah Jane Duff" longdesc="Hannah Jane Duff Home Link" /></a> </div><!--CLOSE DIV FOR LOGO CONTAINER --> </div><!--CLOSE DIV FOR HEADER CONTENT --> <!-- TEMP TAKE OUT AND PUT INTO HEADER AREA --> <div id="mainContent"><!--OPEN DIV FOR MAIN CONTENT--> <div class="centreContent"><!--OPEN DIV FOR CENTRE CONTENT--> <div id="menuContent"><!--OPEN DIV FOR MENU CONTENT--> <div id="menu"> <ul class="menu"> <li><a href="index.html" class="main"><span>Home</span></a></li> <li><a href="" class="main"><span>bio</span></a> <div><ul> <li><a href=""><span>violin</span></a></li> <li><a href=""><span>piano</span></a></li> <li><a href=""><span>singing</span></a></li> <li><a href="" class="parent"><span>teaching</span></a> <div><ul> <li><a href="" class="parent"><span>aberdeen</span></a> <div><ul> <li><a href="#"><span>aberdeen 1</span></a></li> </ul></div> </li> <li><a href="" class="parent"><span>bradford</span></a> <div><ul> <li><a href=""><span>bradford 1</span></a></li> </ul></div> </li> <li><a href="" class="parent"><span>leeds</span></a> <div><ul> <li><a href=""><span>leeds 1</span></a></li> </ul></div> </li> </ul></div> </li> <li><a href="" class="parent"><span>influences</span></a> <div><ul> <li><a href=""><span>classical</span></a></li> <li><a href=""><span>folk</span></a></li> </ul></div> </li> <li><a href="" class="parent"><span>other</span></a> <div><ul> <li><a href=""><span>folk′d</span></a></li> <li><a href=""><span>string quaret</span></a></li> </ul></div> </li> </ul></div> </li> <li><a href="" class="main"><span>publicity</span></a> <div><ul> <li><a href="" class="parent"><span>news</span></a> <div><ul> <li><a href=""><span>may 2011</span></a></li> <li><a href=""><span>march 2011</span></a></li> </ul></div> </li> <li><a href=""><span>gallery</span></a></li> <li><a href=""><span>other</span></a></li> </ul></div> </li> <li><a href="" class="main"><span>recordings</span></a> <div><ul> <li><a href=""><span>all</span></a></li> <li><a href=""><span>new york dolls</span></a></li> <li><a href=""><span>classical</span></a></li> </ul></div> </li> <li><a href="" class="main"><span>contact</span></a></li> </ul></div> </div><!--CLOSE DIV FOR MENU CONTENT--> <div class="paraBlock"><!--OPEN DIV FOR PARA BLOCK --> <p><?php echo $row["pageContent"]; ?></p> </div><!--CLOSE DIV FOR PARA BLOCK--> <div class="clearArea"><!--OPEN DIV FOR CLEAR AREA--> </div><!--CLOSE DIV FOR CLEAR AREA--> </div><!-- CLOSE DIV FOR CENTRE CONTENT--> </div><!--CLOSE DIV FOR MAIN CONTENT--> <div id="footerContent"><!--OPEN DIV FOR FOOTER CONTENT--> <div class="leftFooter"><!--OPEN DIV FOR LEFT FOOTER--> © <?php echo date(Y); ?> All Rights Reserved | Design by <a href="http://www.innovationation.co.uk/">Innovationation UK</a> </div><!--CLOSE DIV FOR LEFT FOOTER--> <div class="rightFooter"><!--OPEN DIV FOR RIGHT FOOTER--> <a href="">Copyright | </a> <a href="">Disclaimer | </a> <a href="">Privacy Policy </a> <a href="">Terms of Use | </a> <a href="">Site Map | </a> <a href="loginArea/login.php">Admin</a> </div><!--CLOSE DIV FOR RIGHT FOOTER--> </div><!--CLOSE DIV FOR FOOTER CONTENT--> <?php } ?> </div><!--CLOSE DIV FOR VIEW CONTAINER--> </body> </html> So I'm trying to create an Array from a comma separated string containing array{s}. How can I take a string full of comma separated hex values such as : <?php $myStr = ( "00ffff", "00cccc", "009999", "007777", "004444", "001111", "01ffff", "01cccc", "019999" ); ?> & turn it into 3 separated arrays like : <?php $myNewArrs = [ Array1 ( 3 ), Array2 ( 3 ), Array3 ( 3 ), ]; ?> which REALLY looks like : <?php $myNewArrs = [ Array ( "00ffff", "00cccc", "009999" ), Array ( "007777", "004444", "001111" ), Array ( "01ffff", "01cccc", "019999" ), ]; ?>
? Thank you & have a great afternoon!
Edited May 27 by AquariaXI OK so here is what I want to do. I have a bunch of strings stored in a table. The strings are like this grandparent.parent.child. some are just parent.child What I want to do is Select all and then put them into an array. soooo x.y.z would become $Var['x']['y']['z'] and a.b would become $Var['a']['b'] It has to be dynamic because some strings are just 2 levels, and it goes all the way up to 6 levels. I have different plans for setting the variably to something but I can handle that. Any ideas? Hi all, Im so stuck on this! Cant figure out a solution... $precip_array[0] has a value of "80" in it as a string. I need to compare it to an integer. echo (int)$precip_array[0] returns a "0". Ive also tried adding a 0 but that results in the same. I did a var_dump on $precip_array[0] which returns string(17) "80" I think 17 signifies the length of the string, but I only see 2 digits when I echo this. Any help is much appreciated. Hi I need to know how to arrange this thing looking something like an array to be able to find values from it. The problem is, I don't really even know what I am dealing with here. Wonder if you could help me out. I have the following mess stored in a $messages variable: {"messages":[{"message_id":2314446,"from":"441234568790","timestamp":1280703181,"text":"first text"},{"message_id":2315147,"from":"123456789014","timestamp":1280755014,"text":"another text"}],"unread":0} and I don't know how to do the following: I need is to get only the message text from any message that matches my wanted phone number. For example: I want to get the text value from message which from is 123456789014. /Henry Hi, I know the problem that I am having is related to the change in PHP5 about strings and arrays, however I do not understand why my script is affected. It seems like I am not trying to add more variables to an array. I do not success in order solve the problem. Help me please: // Build View Array if ($view_result!=false) { $i=0; while ($view_row =@ mysql_fetch_array($view_result)){ $i++; $view_rows[$i] = $view_row; // build view_comments array if ($viewcomments=="yes") { $sql = "SELECT * FROM blog_comments WHERE nBlogId=".$view_row["nIdCode"]." ORDER BY nIdCode DESC"; $result = mysql_query($sql,$con); if ($result!=false){ $j=0; while ($comment_row =@ mysql_fetch_array($result)){ $j++; $view_comment_rows[$i][$j] = $comment_row; } } } } } else { $problem = "2"; } // increment view counter for either the single blog being shown // or ALL blogs being shown //The problem is here if ($view_rows[1]["nIdCode"]!="" && strpos($_SERVER["PHP_SELF"],"admin.php")==false){ if ($viewmode=="single"){ $blogid = $view_rows[1]["nIdCode"]; $sql = "UPDATE blog SET nViews=nViews+1 WHERE nIdCode=".$blogid; } else { for ($i=1;$i<=count($view_rows);$i++){ $blog_array[$i] = $view_rows[$i]["nIdCode"]; } $blogids = implode(",",$blog_array); $sql = "UPDATE blog SET nViews=nViews+1 WHERE nIdCode IN (".$blogids.")"; } $result = mysql_query($sql,$con); if ($result==false){ print "<li>Problem with SQL<br>[".$sql."]</li>\n"; } } } Last edited by sbarros (2011-01-08 18:21:52) If I wanted to print a string that contains a variable that also contains an array, how would I do so? I want to put the resulting echo into a log file. Example: “These are the books: $userArray and these are the pages: $pagesArray”; With just an array, I can use print_r($array, true) to get an array formatted for use in a string (which works well for my purposes) but this doesn’t work with two arrays unless I do this manually. (Such as setting the $user_array = print_r($userArray). But I want to write a function that will take a string, potentially containing arrays (as variables), and interpolate/make them legible for humans. (Some of the arrays are also multidimensional.) But it looks like I can't even concatenate a string and an array. $string = $string . $array. gives an error, array to string conversion. I don’t understand PHP very well so please explain what is going on here. and the best way to record something like the Example above. I have in ONE MySQL database row a string of ID's like this: Name of Row: Values: Post IDs 10 14 52 37 And now I want to fetch those ID's explode them (by the space) and then use them as an array, like this: $array[] = explode(" ", $query); echo $array[0]; // 10 echo $array[1]; // 14 echo $array[2]; // 52 Is this possible, if yes how can I do this? Hi everybody, I need some help about how to convert string to array name. I have the following function which pass $_REQUEST type as parameter. It is not working because I don't know how to convert $method to $_GET or $_POST in a proper way. Do anybody know how? Code: [Select] function validateIfFilled($method, $fields) { $exploded=explode(",",$fields); foreach($exploded as $field){ if(empty($method[trim($field)])){ return false; } } return true; }; if(!validateIfFilled('$_GET', "email, password, address")) ... Thank you!
<?php $srs = array(); for ($section = 1; $section < 5; $section++) { for ($row = $section; $row < 10; $row++) { for ($seat = $row; $seat < 20; $seat++) { $srs[] = array( 'section_name' => $section, 'row_name' => $row, 'seat_name' => $seat); } } } output(convert_array($srs)); // Converts the array function convert_array($input) { return $input; } function output($obj) { echo "<pre>"; print_r($obj); echo "</pre>"; die; } ?>
I'm trying to convert those array number to string, add implode() to make it happen, but seem PHP didn't recognize variable in $input. Like this implode("Section: ", $input) or (Section: ", $srs). Can you help me? Thanks, Gary Edited October 16, 2019 by sigmahokiesHow can I get rid of "Notice:Array to string conversion on line 78" error from this code? can i get a little help please? This is line 78 : $table .= $columnValue; Basically this code's supposed to do is to group the values from grpa, grpb of datatb to 4 different categories according to their value. and as end result, category index number of each category is put into the html table. Thanks.
<?php include ("configd.php"); $sql = "SELECT grpa, grpb From datatb"; $result = $conn->query($sql); //categories $cat = [ 4 => [1, 2, 3, 4], 3 => [5, 6], 2 => [7, 8], 1 => [9, 10] ]; while ($row = $result->fetch_assoc()) { foreach ($cat as $catKey => $catValue) { $columns[$catKey] = array_filter($row, function ($col) use ($cat, $catKey) { if (in_array($col, $cat[$catKey])) { return true; } }); } $output[] = $columns; } // the output $table = <<<EOT <table class='maintable'> <tr><th>9:10</th></tr> <tr><th>7:8</th></tr> <tr><th>5:6</th></tr> <tr><th>1:4</th></tr> </table> EOT; foreach ($output as $row) { $table .= "<table class='maintable'>"; foreach ($row as $columnKey => $columnValue) { $table .= "<tr>"; $table .= "<td>"; $table .= $columnValue; $table .= "</td>"; } $table .= "</tr>"; $table .= "</table>"; } echo $table; ?> Edited June 30, 2020 by mattix small additions. I need to assign unknown array keys and their values to strings. The code I am using is: Code: [Select] $cart = $_SESSION['cart']; $items = explode(',',$cart); $qty = array(); foreach ($items as $item) { $qty[$item] = $qty[$item] + 1; } print_r($qty); The keys change and are not ordered. I do not know what the key or it's value may be. So as an example, I might have: Code: [Select] Array ( [2] => 5 [4] => 8 ) or in a different scenario, I might have: Code: [Select] Array ( [1] => 6 ) What those numbers represent is a product id (the key), and the quantity (the value of the key). Can someone help me to assign these to a string? I have been reading all morning, and not making any progress. Thank you! Hello, I'm going to be sending emails to users from a community calendar showing events for the day or a time frame specified elsewhere. The problem I'm having is turning results of DB query into a string when there are multiple results for the day. It works just fine with single results. I understand why it doesn't work but can't figure out how to solve the problem. Don't worry about the $eventdate as that comes from the same array as the $event_id used to call the array shown below. I tried foreach and implode but couldn't get it working so I'm starting over and asking for your guidance on how is the best way to pull this off. Thanks for your help. Code: [Select] $getevent = mysql_query("SELECT title, description from ".$conf['tbl']['events']." WHERE event_id=$event_id AND private=0"); WHILE ($gtevent = mysql_fetch_array($getevent)) { $event_title=$gtevent['title']; $event_description=$gtevent['description']; $message="<p><span style=\"font-size:24px\">$event_title</span><br />$eventdate</p><p>$event_description</p>"; } Hello I am facing a problem which i can not handle. I appreciate for any help. My Database is: Code: [Select] CREATE TABLE IF NOT EXISTS `shops` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `options` text, `user_name` varchar(250) NOT NULL , PRIMARY KEY (`id`), UNIQUE KEY `user_name` (`user_name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='user data stored' AUTO_INCREMENT=1 ; And some sample data as below: Code: [Select] INSERT INTO `users` (`id`, `options`, `user_name`) VALUES (1, 'apple-orange-grape-bmw-toyota-fig-', 'user1'), (4, 'apple-tomato-pc-notebook-yellow-', 'user2'), (5, 'blue-green-orange-cdrom-', 'user3'), (6, 'orange-yellow-blue-pink-bread-', 'user4'); How can i display how many apples or green or any item selected by user? So far i tried in_array, array_count_values but seems no one is working. Regards Hello, I have a string that contains a directory path much like: "/images/icons" and I want to take that string through a function and explode it into an array of directories that with add my directory structure array: images icons Then if I were to send the string "/data/documents" to the function it would append to the existing array: images icons data documents Here's the code that I've got thus far: <?php $global_structure = array(); generate_structure("./images/icons"); generate_structure("./data/documents"); function generate_structure($directory) { if(!is_dir($directory)) return false; $directory_structure = explode("/", $directory); // do something here to iterate over $global_structure and add new directories to equal to current directory path making the value an empty array. } ?> Hi all, i have this array $str = array("apple is red", "banana is yellow", "pineaple is tropical fruit", "coconut is also tropical fruit", "grape is violet"); i want to find string "coconut" inside $str and put the whole string "coconut is also tropical fruit" into variable $coconut. can i do this? i don't want to use the this code Code: [Select] <? $coconut = $str[3]; echo "$coconut"; ?> can someone help? Thank you, Best Regards |