PHP - Php Associate Array Outputs Only Last Index Key And Value In Another File
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. Similar Tutorials<?php include('header.php'); require('dbcon/dbcon.php'); // if fields in form are set and submitted, check if user exists and is logged in or not if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = $_POST['username']; $password = $_POST['password']; $user_query = $pdo->query("SELECT * FROM profiles001 WHERE username = '$username'"); $row = $user_query->fetchAll(PDO::FETCH_ASSOC); // if username and password match, init session and redirect to another page. if ($row == 1 && password_verify($password, $row['password'])) { $_SESSION['logged_in_user'] = $username; // set to IDnum later on... $_SESSION['username'] = $username; // check if the user is logged in // if so, redirect to main page for logged-in users. if (isset($_SESSION['logged_in_user'])) { $_SESSION['logged_in_user'] = TRUE; header('Location: main.php'); } else { // not logged in, keep on same page... session_destroy(); exit(); } } else if ($username != $row['username'] || $password != $row['password']) { echo var_dump($row); echo var_dump($row['password']); echo var_dump($row['username']); echo var_dump($row['email']); echo "Incorrect username or password."; } } ?> This code is responsible for authenticating the user upon logging in. I went ahead and updated the mysqli portion to PDO. As you can see I var_dump some variables near the end. Variable $row prints out as array(1) { [0]=> array(9) { ["username"]=> string(4) "test" ["password"]=> string(60) "$2y$10$uQEUsIwm0usWyZjWk/vo8e90e867oPLBu3ThKCk1aUseMcQuuHrVq" ["avatar"]=> string(15) "assets/soap.jpg" ["doc"]=> NULL ["las"]=> NULL ["email"]=> string(13) "test@test.org" ["c_status"]=> string(1) "0" ["account_age"]=> NULL ["bio"]=> string(4) "test" } }. The other three print out as NULL. What exactly is going on here? Hi there, Basic question, but I can't seem to find a page in the PHP docs that answers (though I'm sure such a one exists, I just can't seem to think up the right search terms - anyway) My question is: is there a short-hand way to use a value from an associative array as the key in another associative array? So for example, given this array: $the_array = array(0 => array('name': 'the_name', 'value' : 'the_value'), 1 => etc....); then this kind of foreach loop doesn't work Code: [Select] $new_data = array(); foreach($the_array as $element){ $new_data[$element['name']] = $element['value']; } Obviously I can just save out the values, like $name = $element['name'] --- but I was just wondering if there was a more efficient way to do it? Cheers, PS. I tried encapsulating with {} - i.e. $new_data[{$element['name']}] --- but that also fails. Code: [Select] Array ( [Comment] => Array ( [post_id] => 1 [name] => cc [email] => [body] => spam ) ) How can i check if email is empty or not? Is there any php built in function? Should i use foreach? Hi guys, I have a simple query he $sql="SELECT user_id FROM $tbl_name WHERE email='$loginuseremail' AND password='$loginpassword'"; $result=mysql_query($sql); $row = mysql_fetch_assoc($result); //START SESSION session_start(); $_SESSION['username']=$loginuseremail; $_SESSION['user_id']=$row; echo $_SESSION['user_id']; It should obviously output an ID number but instead I just get the word 'Array'. If I remove the mysql_fetch_assoc() I just get 'Resource ID #4'. Can anyone point me in the right direction? Thanks! I have created a basic website which allows users to login and then need to record their location. I have it so they enter their location into a form, but I need to associate the table for users with locations. I used the code: $user = R::findOne('person', 'username=?', array($_SESSION['name'])); $plc = R::dispense('location'); $plc->location = $_REQUEST['location']; $plc->activity = $_REQUEST['activity']; $id = R::store($plc); R::associate($user, $plc ); It returns the error: Catchable fatal error: Argument 1 passed to R::associate() must be an instance of RedBean_OODBBean, boolean given HELP???!!!! Hey guys seem to have tricky question here, I am just wondering how I could do the following:
I have an SQL table that contains these columns:
As you can see there is a 'Make' column and a 'Model' column and each row displays what make it is.
I now want to associate the 'Makes' with the 'Models' in another table just like this example:
BMW AUDI VOLVO FORD TOYOTA
X5 All Road XC90 Focus Supra
3 Series A1 C30 Mustang Yaris
5 Series Galaxy
So for example if the first table has a row that contains the make 'AUDI' within the 'Make' column I then want it to take the value of the 'Model' and list it into my other table under the 'AUDI' column, any ideas how I can do this with PHP?
Thanks!
so I have this code: Code: [Select] <input type='checkbox' name='title8' value='$title8' /></td><td><strong>$title8</strong> <br /> $date8 <br />$ $price8<input type='hidden' name='price8' value='$price8'> how do I make is so that the hidden field is only going to submit if the checkbox is checked........ 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? I've inherited a website and I'm no PHP expert. The way pages work is the urls are displayed as follows http://www.website.com/?action=<page_name> The pages are stored in a folder called templates as .tpl files. Amongst these is a file called layouts.tpl which is the website layout and menus, inside this there's a php include Code: [Select] <?php include("template/$content_for_layout.tpl"); ?> which basically draws the content for the page from each static file when requested. In the index.php each static file has to be included as in the following example: Code: [Select] case "conditions"; $title = "Terms & Conditions"; $content_for_layout = $_GET['action']; break; Without this in the index.php the page just reverts back to the homepage when you enter the url. I personally don't think this is right? It is handy to be able to manage all the page titles from a central location (index.php) but seems quite messy and cumbersome. I plan on making an articles or news folder and regularly creating pages and if each one has to be relayed this way in the index it is going to get big and cause headaches. Is there any way around this that anyone can see? ... On another note. If you type in the actual physical url of the file location it shows the html of the page without the layout i.e. http://www.website.com/template/conditions.tpl I don't know how common it is for websites to display "../?action=pagename" or similar but I wouldn't have thought it would be ideal for SEO purposes? I'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. Sorry,guys,just can`t get thru: 1.there`s a file index.php <html> <body> <form action=/open.php> <button name=Jack value="150" type=submit>Send Form</button> </form> </body> </html> 2.there`s another file open.php <? echo $Jack; ?> Press the button,in the address box it says: http://mysite.net/open.php?Jack=150 But nothing happens,open.php doesn`t work.I got Denwer,open.php is in www.mysite.net. Please,help.Thanx. Hi everyone! Nice to meet/see/read you. This is my first post and it will probably be a lame one so apologies. I'm a pretty good frontend designer and I've always struggled to learn PHP and my new job is forcing it on me so I'm happy in a "throw me in the deep end" kinda way. I am really stuck! I have a single page that is using jquery to scroll my content left and right via the menu (example attached). What I am trying to do is when on the homepage, don't show the "main logo". When on any other link, show it. I immediately thought of an if/else statement but realised I don't know what or how exactly to target since everything is on the same page and the URL doesn't change. Could I target the image title that is the only image on the homepage? So, something like: <?PHP $image_title = 'home'; if (XXXXX($image_title)) { echo "IMAGE"; } else { echo "NO IMAGE"; } ?> I know that's wrong, I put XXX where I feel like something possibly helpful should go. Heh. I'm not asking for someone to write code for me, I'm happy to learn but but I would be very grateful if someone could just guide me to what I need to do and off to Google I will go. I haven't been able to find anything that is like: "if image title equals". Hmm... I hope I can do this with PHP. Thanks again, Linda 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?? <?php $i = 2; $i = $i++; echo $i; ?>Output of above code is 2. <?php $i = 2; $p = $i++; echo $i; ?>Output of above code is 3. Why this difference? I mean how these codes are processed to give an output? 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); 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 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 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. 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>"; ?> |