PHP - Array Index Changes
I tried searching for this but I didn't find anything. I have some php code that when loaded from a web page draws some numbers from a database and outputs. Should be no problem I thought
The code involves a mysql query. This is an edited sample: $query = "SELECT `count` FROM `uc` WHERE `id` = 17"; $result = mysql_query($query, $dbh) or die(mysql_error()); $row = mysql_fetch_array($result, $dbh); Now after this I normally access $row as $row[0] and this works great most of the time. However about 10% of the time it returns an error: "Notice: Undefined offset: 0" My investigation using print_r($row); shows that sometimes it returns Array ( => 619 ) and sometimes it returns Array ( [count] => 619 ) Why the inconsistency? How can I make it always use a numeric index? Similar TutorialsI've got a multidimensional array that has 2 columns. The first column is numerical (country_id), and the second column is text (country_name), which may or may not be data that will be turned into an array. Looks something like this: column 1 (index 0) = 42 column 2 (index 1) = Great Britain|England I use a while loop to create an array of these rows, then a use a foreach loop to go through index[1] of each row. If there is a single name for a country, it is added to a new array, but if there is more than one name for a country, then both names are added to the new array. So, for example, if we had this data: row1 column 1 (index 0) = 12 column 2 (index 1) = Algeria row2 column 1 (index 0) = 22 column 2 (index 1) = Ethiopia row3 column 1 (index 0) =42 column 2 (index 1) = Great Britain|England Then the final array would look like this: index[0] = 12 index[1] = Algeria index[0] = 22 index[1] = Ethiopia index[0] = 42 index[1] = Great Britain index[0] = 42 index[1] = England Now I would like to sort by index[1] to get the following alphabetical order: index[0] = 12 index[1] = Algeria index[0] = 42 index[1] = England index[0] = 22 index[1] = Ethiopia index[0] = 42 index[1] = Great Britain What do I use? I've fooled around with sort, usort, asort ... can't figure it out. Thanks in advance. Hi- I did this and it works... based on the date, the values in the array (from 1 to 9) are echoed by calling $num. Code: [Select] <?php $start = "2012-02-27"; $now = date("Y-m-d"); $week2 = strtotime(date("Y-m-d", strtotime($start)) . " +1 week"); $week2_st = date("Y-m-d", $week2); $week3 = strtotime(date("Y-m-d", strtotime($start)) . " +2 weeks"); $week3_st = date("Y-m-d", $week3); $week4 = strtotime(date("Y-m-d", strtotime($start)) . " +3 weeks"); $week4_st = date("Y-m-d", $week4); $week5 = strtotime(date("Y-m-d", strtotime($start)) . " +4 weeks"); $week5_st = date("Y-m-d", $week5); $week6 = strtotime(date("Y-m-d", strtotime($start)) . " +5 weeks"); $week6_st = date("Y-m-d", $week6); $week7 = strtotime(date("Y-m-d", strtotime($start)) . " +6 weeks"); $week7_st = date("Y-m-d", $week7); $week8 = strtotime(date("Y-m-d", strtotime($start)) . " +7 weeks"); $week8_st = date("Y-m-d", $week8); $week9 = strtotime(date("Y-m-d", strtotime($start)) . " +8 weeks"); $week9_st = date("Y-m-d", $week9); $var_name = array('1', '2','3','4,'5','6','7,'8','9'); if ($now <= $week2_st){ $num = $var_name[0];} elseif($now >= $week2_st && $now <= $week3_st){ $num = $var_name[1];} elseif($now >= $week3_st && $now <= $week4_st){ $num = $var_name[2];} elseif($now >= $week4_st && $now <= $week5_st){ $num = $var_name[3];} elseif($now >= $week5_st && $now <= $week6_st){ $num = $var_name[4];} elseif($now >= $week6_st && $now <= $week7_st){ $num = $var_name[5];} elseif($now >= $week7_st && $now <= $week8_st){ $num = $var_name[6];} elseif($now >= $week8_st && $now <= $week9_st){ $num = $var_name[7];} elseif($now >= $week9_st){ $num = $var_name[8];} else{ $num :'( = $var_name[0];} ?> I'm trying to do a for loop so the index # increments by one and i only call $r instead $var_name[0], $var_name[1], $var_name[2], and so one. Any ideas? Code: [Select] $count = count($var_name); for ($i = 0; $i < $count; $i++) { $r = $var_name[$i]; } I am wondering whether there is a way to do a foreach loop for an array, without starting at index[0]. Say, for example, I wanted to start displaying the contents of a 20 item array starting at index 5, what is the best way to do it? I know of this way, but it seems too crude (ie. there has to be a better way): $count = 0; foreach($array as $item) { if ($count > 5) {echo $item;} $count++; } Any other ideas?? Here is my function which almost works as expected: <?php function find_value($array,$value) { for($i=1;$i<sizeof($array);$i++) { if($array[$i] == $value) { echo "$i . $array[$i]<br />"; return; } } } ?> And I call the function like so: <?php $names = array('Jason','Mike','Joe'); $name = 'Joe'; find_value($names,$name); ?> And the output is: 2 . Joe According to my understanding of Arrays, Joe would be index 3 BECAUSE my counter starts at 1 in my for loop??? Why is the result like this? What am I not understanding here? I am just trying to use Associate array in another php file through session.
file1.php <?php $age = array(); $_SESSION["age"] = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); foreach($_SESSION["age"] as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>\n"; } ?> OUTPUT: Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43 file2.php <?php session_start(); foreach( $_SESSION["age"] as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>\n"; } ?> OUTPUT: PHP Notice: Undefined index: age in session.php on line 3 PHP Warning: Invalid argument supplied for foreach() in session.php on line 3 Why am I getting this error? Above is just example I tried to demonstrate for asking question for other issue, unfortunately I got new error in this example. But actual issue was, I was trying to plot graph using library which requires only Associate array, where the data is formed in file1.php. But I get only last index value displayed in file2.php even in graph or in echo. I don't understand why other values are not displayed in file2.php Please point me what is going wrong, Thanks. I have this code Code: [Select] $nArr = array('A', 'B', 'C', 'D', 'E', 'F'); $counter = 3; while ($counter > 0) { $chunkedValues[$counter][0] = 1; for ($j = 0 ; $j < $counter ; $j++) { $chunkedValues[$counter][$j + 1] = $nArr[$j]; } $nArr = array_slice($nArr, $counter--); } var_dump($chunkedValues); that outputs: Code: [Select] array 3 => array 0 => int 1 1 => string 'A' (length=1) 2 => string 'B' (length=1) 3 => string 'C' (length=1) 2 => array 0 => int 1 1 => string 'D' (length=1) 2 => string 'E' (length=1) 1 => array 0 => int 1 1 => string 'F' (length=1) But i need this index structu Code: [Select] array 0 => array 0 => int 1 1 => string 'A' (length=1) 2 => string 'B' (length=1) 3 => string 'C' (length=1) 1 => array 1 => int 1 2 => string 'D' (length=1) 3 => string 'E' (length=1) 2 => array 2 => int 1 3 => string 'F' (length=1) I want to avoid loops with ceil. Any idea? thanks for your time. I have this code working fine (thanks to Thorpe). FYI, this code is getting info for each day and putting that info into the array and then later on a calendar is generated and the data gathered here is placed onto each specific day. This is working EXCEPT when there are MULTIPLE data sets on the SAME day. In those cases, it's just displaying the first data set. In other words, if $hunches['day'] = 3 and there is just one data set with that date, it will display that info on the calendar fine. But if there are five data sets with $hunches['day'] = 3, then it only displays the first one. I need it to display all data sets, so any clue how I could alter this code to do that? Code: [Select] $sql = "SELECT *, DATE_FORMAT(`dob`, '%e') AS day FROM hunches WHERE poolid = '{$_GET['poolid']}' AND (DATE_FORMAT(`dob`,'%m')) = " . $month1 . " ORDER BY day"; $gethunches = mysql_query($sql, $connection); if (!$gethunches) { die("Database query failed: " . mysql_error()); } else { while ($hunches = mysql_fetch_array($gethunches)) { $days1[$hunches['day']] = array(NULL,NULL,'<span class="red">' . $hunches['firstname'] . '</span>'); } } Here is a further explanation... Say $hunches['day'] = 5 and there are four data sets for that day (with respective firstnames of Bob, Joe, Jim and Tony). I would essentially need this to happen in the code... Code: [Select] $days1[$hunches['day']/*which would be 5 in this example*/] = array(NULL,NULL,'<span class="red">' . $hunches['firstname'] . '</span><br> <span class="red">' . $hunches['firstname'] . '</span><br> <span class="red">' . $hunches['firstname'] . '</span><br> <span class="red">' . $hunches['firstname'] . '</span>'); And that would then output... Bob Joe Jim Tony ...in the 5th day box on the calendar. Right now, I'm just getting... Bob I fear this is very complicated to do but holding out hope that there is some relatively easy way to make this work. I'm using the code below to on echo certain words based on their index/key value, this works fine however, im trying to only do this in exploded quotes... the problem is, exploding quotes turns the portion into an array which cant be passed to str_word_count... how can i do the same thing only inside quotes. So that hello world "this is a test" would become: Code: [Select] Hello World This [0] => Is [1] => a [2] => Test [3] Im trying to always remove say the 4th word in quotations, or maybe the 3rd and 4th, whatever i want to omit i leave out from the echo, so echo $data[0].' '.$data[3].'; would output "This Test" omitting "Is A" Code: [Select] $data = 'hello world "this is a test"'; $data = str_word_count($data, 1); echo $data[1].' '.$data[2].' '.$data[0]; I have been researching php.net regain the function parse_ini_file() I know you can pass it an actual ini file but what if you already saved the ini file as a string and saved the string in a variable can you pass that variable to the function? I am getting the following error Code: [Select] [function.parse-ini-file]: failed to open stream: No such file or directory in this is how I am calling it. Code: [Select] $settings = parse_ini_file($data); echo $settings["mac"]; <? $array = array('eggs', 'bacon', 'football', 'baseball', 'ford', 'toyota'); $rand_index = mt_rand(0, count($array) / 2 - 1) * 2; ?> <?php echo "$array[$rand_index]"; ?><?php echo "$array[$rand_index+1]"; ?> i dunno why this doesn't work. I want to echo both values three of the pairs such as eggs bacon or football baseball Good morning! I have a two dimensional array, basically a table (see code below). I want to get a value from the array using two methods: 1) Using the row's key: $NewValue = $MyArray[$UniqueKey]; 2) Using the row's index (row number, so to speak): $NewValue = $MyArray[$RowNumber]; The second print statement in the code below does not work. Both print statements should output the same value. Is there an easy way to do this? The table has hundreds of rows and I will not know the key value of row 879 nor can I generate it. So I cannot use array_keys(). And I DO NOT want to start at the first row and count up to the 879th row. Any clever ideas to share and enlighten? Thanks! <?php // Initialize the array keys and values $MyArray = array(); $MyArray['first']['col1'] = 'abc'; $MyArray['first']['col2'] = 'def'; $MyArray['first']['col3'] = 'ghi'; $MyArray['second']['col1'] = 'jkl'; $MyArray['second']['col2'] = 'mno'; $MyArray['second']['col3'] = 'pqr'; $MyArray['third']['col1'] = 'stu'; $MyArray['third']['col2'] = 'vwx'; $MyArray['third']['col3'] = 'yz'; $MyArray['fourth']['col1'] = 'a1a'; $MyArray['fourth']['col2'] = 'b2b'; $MyArray['fourth']['col3'] = 'c3c'; $MyArray['fifth']['col1'] = 'ddd'; $MyArray['fifth']['col2'] = 'eee'; $MyArray['fifth']['col3'] = 'fff'; // Two methods to get a value. Second one does nothing. print"{$MyArray['third']['col2']}</br>"; print"{$MyArray[2]['col2']}</br>"; ?> I have an associative array that is serialized and stored in a MySQL DB. The array is a duty roster for my son's Cub Scout camping trip (adult volunteers for specific jobs). When a user clicks a spot on the jQuery/client side, it sends it to my php page via ajax, which should pull up the array from the DB, unserialize it, replace the value "Available" with the person's name for the date/time/job that they clicked on. For ease of processing, I need to reference the value to replace by numerical indexes rather than the associative key string-type name, but when I try it, it just says Undefined offset. I thought I could access key/values using the numerical index in square brackets, just as I could if it were a non-associative array. What gives? (You can see near the end where I tried to access the array by index; this now-commented out line just tacked it on at the end, like it was recognizing the digits as strings instead of integers. I've tried to cast the values as integers before putting them in brackets, but same effect. Code: [Select] // get the duty roster array from the database $query = "select dutyroster from ".$eventsTable." where eventID = 1"; $result = mysql_query($query); if(!$result) { } else { //put the returned result into a usable array $returnedRows = mysql_fetch_array($result,MYSQL_BOTH); $unserializedArray = unserialize($returnedRows[0]); } //get the returned values for ID, email, and fillerValue $ID = "0-0-2-2";//$_POST['ID']; $email = "blank@blank.com";//$_POST['email']; $fillerValue = "Dude (test)";//$_POST['fillerValue']; // parse $ID to break out the array index & set them as variables $explodedArray = explode("-",$ID); $iDate = (int)$explodedArray[0]; $iTimeblock = (int)$explodedArray[1]; $iJob = (int)$explodedArray[2]; $iSlot = (int)$explodedArray[3]; echo "<br/> the values a idate: ".$iDate." and iTimeblock: ".$iTimeblock." and iJob: ".$iJob." and iSlot: ".$iSlot."</br>"; echo "<BR/> the random selected value to display is: ".$unserializedArray[0]; //$unserializedArray[$iDate][$iTimeblock][$iJob][$iSlot] = $fillerValue; print_r($unserializedArray); I wish to return the object in an array with the highest index where its index falls between between integers, and return null should one not exist. For instance, with the following and a min and max of 10,000 and 15,000, it should return OBJ4, and with a min and max of 15,000 and 20,000 it should return NULL. Any thoughts? Thanks function getObj(int $min, int $max):?OBJ { $list=[ 12314=>'OBJ1', 321=>'OBJ2', 42142=>'OBJ3', 14314=>'OBJ4', 123=>'OBJ5', 13314=>'OBJ6' ]; return getIt($list, $min, $max); }
hi very good, hi very good, I have a label on a form select and I get that value with $ _POST like this: $ _POST like this: $ gallery = array ($ _POST ['gallery']); and that value will put it he $ image = $ sitemap-> gallery [$ gallery] -> addChild ('image'); the problem is giving me error is as follows: Fatal error: Call to a member function addChild () on a non-object in I do not understand is that if I put a value directly asin me do it like so: $ gallery = 0; $ Image = $ sitemap-> gallery [$ gallery] -> addChild ('image'); I do well, what happens is that I want the user to choose, Kind of strange as it may fix. I really dont no what the problem is and im new here so i dont no if this is the right place to put this but im trying to make a registration page for my server and when i bring it up it says Undefined index: action in C:\xampp\htdocs\index.php on line 56 and idk what to do >.< this is the line that has the problem if($_POST['action']!="signup") so hopefully u guys could help me :/ Im using xampp btw Hi there, I was wondering if there is a way to display content on only my index.php page? I believe there is a way and I have done it before, but some of my pages use index.php?category etc. Is there a way to show content just on index.php and not on any dynamic pages? Thanks i'm running code on what i only want to be the HOME page, but the current site it built using GET variables with index.php needless to say, the home page is accessed either as domain.com/ or domain.com/index.php - i'm hoping someone can show me how to check for this condition, that it is only index.php without anything further I'm only slightly familiar with $_SERVER['uri'], etc... So i don't know just what to ask. thanks for anyone's help. Glenn An open question this, and one that may or may not bear fruit. But here we go anyway. index.php is a special case I feel because it is often the default script that is called for a web site. Moreover, I keep mine in the freely available root directory, but the rest of my php is out of the root for security purposes - in a directory called "lib". The app I am working on at the present time requires that a user logs on first. So, the code I have in my index.php is very simple: Code: [Select] <?php /* Require Log In */ require("lib/ezLogin.php"); ?> This at least is what I have presently. So I have a few questions: 1. Is treating index.php as a special case, a reasonable approach would you say? 2. Is the separation of the rest of the non-client php files a real security improvement? 3. When you declare the css path, do you use absolute path names? If so, how might it be done so it will work on local (testing) AND the main server (production) with no code change? 4. includes_path - I assume this is the path to the includes directory. However, I am not sure/happy/comfortable with this just yet. Can more than one path be included in this? (I have Googled around but still unhappy) If so, how so? Does this approach works across platforms? If not, is there a way to make it? Many thanks for any help. S I have two files an sample.html which has just a search box some javascript on it to display images when users start typing on this search box. the sample.html works when i entre localhost\index.html now, i have an index.php. when i include("index1.html"); the search box appears but the javascript does not work? why? do i need to relink the following in my sample.html??? <script type="text/javascript" src="autocomplete/lib/jquery.js"></script> <script type='text/javascript' src='jquery.autocomplete.js'></script> <link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" /> fyi i am using wordpress. So I've searched for a few hours already, and decided to give in to asking on a forums. On the site I'm working on, I want the navigation to look like www.website.com/index.php?id=2 instead of www.website.com/contacts.htm Also, the way I did it before, I renamed my main home page as 'main.php' and when you go to the site, index.php will display what's on main.php, but will still show www.website.com/index.php?id=1. I've done it before a few years ago, but I lost the site and forgot how to do it. I'm pretty sure there's a if/else if statement that comes into play, but I don't remember. I hope this all makes sense. Thanks |