PHP - Question About Associative Arrays Stored In Super Global Array $_session
Hey all,
I'm well aware of associative arrays (key/value pairs) and how you can index them in an array like this: $character = array (name=>"John", occupation=>"Programmer", age=>22, "Learned language "=>"PHP" ); Then it makes sense to iterate through the key/value pairs of the array using foreach: foreach ( $character as $key=>$val ){ print "$key = $val<br>"; } However, I was watching a video tutorial where he created a $_SESSION array and then created an array associative array: $_SESSION['cart'] = array(); [/PHP] Then he added a function add_to_cart: function add_to_cart($id){ if(isset($_SESSION['cart'][$id])){ $_SESSION['cart'][$id]++; return true; } else { $_SESSION['cart'][$id] = 1; return true; } return false; } Now that $id variable holds an id converted to integer from the dataabse. So if first item is clicked, id holds a value of integer 1. When I see this: $_SESSION['cart'][$id] I see an array that holds two indexes, each index containing an associative array: [[array() => ''], [1 => '']]. So at index 0 of $_SESSION is [array() => '']. But then he uses the foreach iterator like this: function total_items($cart){ $items = 0; if(is_array($cart)){ foreach($cart as $id => $qty){ $items += $qty; d } } return $items; } Now I'm very confused. As you can see in that foreach method, it says that $id (and its corresponding value) is an associative array of $cart array, not $_SESSION array. I don't see how that happened. I thought $cart and id$ were distinct indexes of $_SESSION. I don't see how $id is a key of the $cart array. Thanks for any explanation to clear my confusion. Similar TutorialsI am having trouble understanding what this means: foreach($_SESSION['cart'] as $product_id => $quantity) I look forward to any responses in advance. Just wanted to know if $_Session was a global thing or does php require cookies setup?
I assumed that I could do something like this:
PAGE: A.php session_start(); $_Session['Cat'] = 'Meow'; // ----------------------- PAGE: B.php if (isset($_Session['Cat']) && !empty($_Session['Cat'])){ echo $_Session['Cat']; } OUTPUT: Meow // ----------------------- PAGE: C.php if (isset($_Session['Cat']) && !empty($_Session['Cat'])){ echo $_Session['Cat']; } OUTPUT: MeowI can't seem to get this to work. Page: Handler.inc // ========================================================= Session Log in / out public function logon($username, $password){ if ($username == "admin" && $password == "coffee"){ session_start(); $_SESSION['USER_STATUS'] = '1'; echo 'IN SESSION LOGIN HANDLER'; echo $_SESSION['UserLogged']; } } public function logout(){ $_SESSION['USER_STATUS'] = '0'; echo 'IN SESSION LOGOUT HANDLER'; session_destroy(); //session_unset(); }Page: index.php if (!isset($_SESSION['USER_STATUS']) && empty($_SESSION['USER_STATUS']) || $_SESSION['USER_STATUS'] == 0){ if (isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password'])){ $username = $_POST['username']; $password = $_POST['password']; echo $handler->logon($username, $password); } <LOGIN FORM CODE> }else{ if (isset($_SESSION['USER_STATUS']) && !empty($_SESSION['USER_STATUS']) || $_SESSION['USER_STATUS'] == 1){ echo 'Session name: '. $_SESSION['USER_STATUS']; } if (isset($_POST['btn_logout']) && !empty($_POST['btn_logout'])){ $handler->logout(); echo '<br />Logged out<br />'; } <LOGOUT FORM BUTTON CODE> }Could someone point me in the right direction please. It does not seem to hold its session. I have an array that has several amounts (based on $$$ sales) attached to a 'name' 'id' and 'goal'. As you can see some of the names, id's, and goals are the same. My goal is to gather a total of amounts and attach each total to whichever 'name', 'id', and 'goal' that made the sale. I'm honestly not sure how to go about this as I'm still learning. Probably easiest to explain what I am trying to do, to illustrate the impasse I have came to. I have online store With a number of products. Visitors can click on products, clicking brings details of the product came up in a frame on the right (with a field to enter the quantity), which can than be added to the shopping cart in a separate frame below it bottom right (passed using a different script (the one which I am having issues with)). So each time a product is added to the cart, three dynamic fields are passed via post script, which are named "product_name", "unit_quantity" and "unit_price" (these are all hidden fields called from a sql database based on what product the user clicked on). So for the shopping cart, I want to incorporate an associative array using the three dynamic fields described above("product_name", "unit_quantity" and "unit_price") within a session so that a number of products can be added (hence using an array rather than a variable). So shopping cart i have done so far reads: <?php session_start(); if (!isset ($product_name) && !empty($product_name)) { if (!session_is_registered("product_info")) { $pos=0; session_register("pos"); $product_info[$pos]= array ( 'product_name'=>$product_name, 'unit_quantity'=>$unit_quantity, 'product_quantity'=>$unit_quantity * $unit_price); session_register("product_info"); } ?> Not sure (as I am new to sessions, how to call the array to the screen). I have read through past threads but have not been able to found anything similar to what I am trying to achieve). "Cannot find search daemon". I tried. I've been wracking my brain for the last two hours trying to simplify this. It seems like I'm running over the two arrays far too many times, and that I should be able to do it in one pass somehow. I have two associative arrays, the first contains a set of older options (previous version), the second is a default set of new options. I want to compare the two arrays, and strip out any old options that aren't in the new set. I want to add options from the new set that aren't already in the old, and I don't want to overwrite and of the old options that already have values. Here's a copy of the sandbox I've been working it out in; it works, but it does four separate operations on the arrays to achieve the result: http://pastebin.com/erbFujkG Hi, I have this problem I really hope someone can help me with. I have a variable that stores several arrays. The content of the variable is as follows: Code: [Select] print_r(array_values($array)); Array ( [0] => Value 0) [1] => Value 1) [2] => Value 2) [3] => Value 3) ) Array ( [0] => Value 4) [1] => Value 5) [2] => Value 6) [3] => Value 7) [4] => Value 8) ) Array ( [0] => Value 9) [1] => Value 10) [2] => Value 11) [3] => Value 12) [4] => Value 13) ) Is there a way to join this multiple arrays into a single array? I do not need to keep the Key, as all of the values contains text that I only want to sort with sort();. If I sort it like this, it will only come out as a,b,c,d - a,b,c,d, not a, a, b, b, c, c, d, d and so forth. The php script that creates this array is as follows: Code: [Select] while($row = mysql_fetch_array($run_mysql_query)){; $models = $row['text_value']; $attribute1 = $row['attribute1']; $attribute2 = $row['attribute2']; $array = explode(',', $models); foreach($array as &$value) { $value = $row['varchar_value'] . " - " . $value . " - " . $attribute1 . " - " . $attribute2; } I will appreciate any help! I already know how to empty individual $_SESSION[""] array elements, but I was wondering how you could empty ALL $_SESSION array elements without having to write out unset ($_SESSION[""]); for each one? Is it just unset ($_SESSION);? Sorry if this seems like a stupid question, but I'm just trying to make sure, because I have a lot of $_SESSION variables and am trying to simplify the task of emptying them all. Hi, i am having trouble retriving data from a 2D array in my php code an was wondering if i should be using a session array instead to keep track of the contents of the array between refreshes of the page. I am currently working with an array in the form of : $hosts[][] // $hosts[$x][0] - the hostname // $hosts[$x][1] - the ip address // $hosts[$x][2] - the operating system However, i seem to loose the ability to read data from this array when the user creates a refresh event (ie clicks a button/hyperlink). Should i be storing the data in a $_SESSION array, if so what is the correct syntax to use, i have only ever stored single values in $_SESSION variables. Thanks for reading. Hello again, I got a problem with one of my pages that uses MySql. I didn't expect my site to shoot up into the 1000's per hour but it has but has destroyed the loading time of one of my pages. Below is the function that is super slow! Code: [Select] function get_top($timeframe='today', $time=10, $friends=true, $limit=5, $unique=true, $me_only=false){ if($friends===false){$q='';}else{ $q=' AND (username IN ('; // This array can have upto 500 items in it. global $friend_id_array, $me;$tarray=$friend_id_array; $tarray[]=$me['id']; $x= implode(',',$tarray);$q.=$x; $q.= '))'; } if($me_only){ $q=' AND username = \''.$me['id'].'\' '; } if($timeframe=='today'){ $q_timeframe='AND DATE(thedate) = DATE(NOW()) AND YEAR(thedate) = YEAR(NOW())'; // Checking the date could be slow }else if($timeframe=='week'){ $q_timeframe='AND WEEK(thedate) = WEEK(NOW()) AND YEAR(thedate) = YEAR(NOW())'; }else if($timeframe=='month'){ $q_timeframe='AND MONTH(thedate) = MONTH(NOW()) AND YEAR(thedate) = YEAR(NOW())'; }else if($timeframe=='all'){ $q_timeframe=''; } if($unique){$q_unique='GROUP BY username';} $query="SELECT MAX(score) as highscore, username, timeframe, thedate FROM other_click WHERE (timeframe = '$time') $q $q_timeframe $q_unique ORDER BY highscore DESC LIMIT 0, $limit"; // A very long query $result=@mysql_query($query)or die(mysql_error()); if(@mysql_num_rows($result)>0){ while($row=@mysql_fetch_array($result)){ // Maybe resorting the array makes it super slow $id_array[]=$row; } return $id_array;}else{return false;} } I've commented the lines which I think maybe making this page load slowly. I also thought the way the page is loaded. The page is called 6 times per user but with different settings eg, Friends only and only scores added today. Please help because this is crippling my site. Thank-you all Paul Using: $file = fopen("file1.txt", "r") or exit("Unable to open file!"); I have multiple files (file1.txt, file2.txt, etc.) how can I edit this so it just takes ANY file that ends in .txt and opens it? Good morning! I've spent hours on this to no avail. My understanding is that unset() only deletes the copy of the variable local to the current scope. But I am getting a very different result. I have the following structure and output. What am I doing wrong? <?php first_function(); second_function() { for ($count = 0; $count < $max; $count++) { $my_array = array[]; //initialize my array, local in this scope but can be called global in nested functions print_r($my_array ); //print 1: array should be always empty but is only in empty in FIRST loop. third_function(); //fills the array with numbers, see below, nested function declaring a global array print_r($my_array ); //print 3 of my_array, should be full of numbers from third_function global changes unset($my_array); //delete my array so I can start with new array in next loop print_r($my_array ); //print 4 of my_array, should be unknown variable print('End one loop'); } } third_function() { global $my_array; //declare my global variable //...fill my now global array with stuff... print_r($my_array ); //print 2: should be filled with numbers. And it is. } ?> My output amazingly looks something like this Array() Array(45,48,38...all my numbers...) Array() ERROR: Notice -- Undefined variable: my_array End one loop Array(45,48,38...all my SAME numbers again as if array was NOT unset...) ...... The first and second print lines make sense. But shouldn't the third line be the array filled with numbers generated in third_function? The fourth line error makes sense as the variable is unset. But WHAT did I unset? The next time around in the loop, the array contains the SAME numbers from the previous loop and my new numbers simply get appended to the end of the ever growing array. Why? This should not be that difficult but seems to be driving me crazy. Any help would be greatly appreciated. alexander 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. I have a associative array and I need to compare it to a normal array. Code: [Select] associative will have anywhere from 2-8 of these ['name'] ['color'] ['uid'] Code: [Select] normal array will have anywhere from 1-8 names ['name'] What I need to do is get the name of the people that are in the associative array that are not in the normal array. I've tried all sorts of different loops and what not and I cant seam to get anything to work in every case. Hello, I am not sure if you can help me or if this is the place but... I am running linux and php5.3.6 I am having problems that I did not experience on my Windows box and it has to do with arrays if ($answer['correct']) { (which contains 1 or 0) is throwing Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING removing the quotes works but just curious why it is not working and if there is a setting i can change Also $answers[] = $answer[id]; is throwing Parse error: syntax error, unexpected ']', expecting T_STRING or T_VARIABLE or T_NUM_STRING Thank you to anyone who might be able to help. Hi guys. I have an associative array called $VisitorCountryID $VisitorCountryID = filter_countries(array('Country' => $_SESSION['UserCountryName'])); and the function filter_countries() returns all the information relating to the visitors country from the database. To find out what we have in the array, we do: print_r($VisitorCountryID); and it gives us: Array ( [14] => Array ( [CountryId] => 14 [Country] => Australia [FIPS104] => AS [ISO2] => AU [ISO3] => AUS [ISON] => 36 [Internet] => AU [Capital] => Canberra [Comment] => ISO includes Ashmore and Cartier Islands,Coral Sea Islands [sortOrder] => 1 ) ) Which is OK. Now i just want the CountryId which you can see in the array is 14 therefore I write: print_r($VisitorCountryID['CountryId']); Which should give me 14 but it return blank no output. I am surprised. What do you think is missing here. Any response / feedback always welcomed! Cheers! I WANT HELP WITH ASSOCIATIVE ARRAY THERE IS ARRAY LIKE THIS $ARRAY= array( 'dd'=>1, 'dde'=>233, 'qww'=2231 ) i want to store this array in database which data type i should i use want to use mixed data mixed string-numeric type which data type is suitable and i want to print indexes only but values only what should i do Hello all!! I need help with an associative array I've been working on. I'm not sure if I should have typed the weekday in the index because I'm supposed to use the getdate() function to pull the day of the week into the array. I'm also supposed to use string functions to pull apart the value where it's connected with the colon ":". I've tried using explode() and strtok but I don't quite understand how they work...just like the getdate()..I don't understand. Thanks for any 'nudge' in the right direction you can offer. Code: [Select] <?php $title = "Associative Array"; $heading = "Daily Specials"; $specials = array( "Sunday" =>"52in Flat Screen TV:425.00", "Monday" =>"Amplifier:145.00", "Tuesday" =>"HP Computer:355.00", "Wednesday" =>"500GB External Harddrive:99.00", "Thursday" =>"Internal Speakers:55.00", "Friday" =>"Ergonomic Keyboard:85.00", "Saturday" =>"Wacom Tablet:175.00", ); echo "<html> <head> <title> $title </title> </head> <body> <h1> $heading </h1> <pre>\n"; //prints left and right aligned headers with 30 spaces printf ("%-30s%30s\n", "Items", "Price"); printf ("%'-60s\n", ""); foreach ($specials as $key=>$value); { //prints the key left aligned and the value right aligned //formats to two decimals spaces printf ("%-20s%20.2f\n", $key, $value); echo " </pre>\n"; $delimeter=":"; $inventory=strtok($inventory,$delimeter); while(is_string($inventory)) { if($inventory) { echo " $inventory\n"; } $inventory=strtok($delimiter); } $inventory=explode($delimeter,$inventory); foreach ($items as $item=>$price) { echo" $item, $price\n"; } echo " </pre>\n"; "</body> </html>\n"; ?> Hi guys, I'm really struggling trying toremove duplicates from an associative array. I've tried array_unique but it doesn't work. Can you point me in the right direction please? I'm populating my array using the following code Code: [Select] foreach($category['manufacturers'] as $manufacturer) { list($name, $id) = explode("|", $manufacturer); $brands[] = array("id" => $id, "name" => $name); } If the array contains: id = 1, name = brandA id = 2, name = brandB id = 1, name = brandA I'd like to remove either the first or third entry. I always struggle with associative arrays Hello I have been taking a look at associative arrays. I 'sort' of get the key/value idea, but I'm not quite sure if they appropriate for use with 3 items (as opposed to the 2 key/value items.) In the code below, I can incorporate the 'company' and 'table' values - but I'm not sure how to add the 'id' value (from the query). I would very much appreciate some guidance here. Thank you. Code: [Select] $a = array(); // 'A' table array $b = array(); // 'B' table array $c = array(); // 'C' table array $query = "SELECT id, company, `table` FROM EXHIBITORS WHERE year = $year ORDER BY company ASC"; $result = mysql_query($query) or die("There was a problem with the SQL query: " . mysql_error()); if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $testCol = substr($row['table'], 0, 1); if ($testCol == 'A') { $a[$row['company']] = $row['table']; } else if ($testCol == 'B') { $b[$row['company']] = $row['table']; } else if ($testCol == 'C') { $c[$row['company']] = $row['table']; } } echo "<table>"; foreach($a as $key => $value){ echo "<tr><td>company: $key</td><td>Table: $value </td></tr>"; } echo "</table>"; echo "<table>"; foreach($b as $key => $value){ echo "<tr><td>company: $key</td><td'>Table: $value </td></tr>"; } echo "</table>"; echo "<table>"; foreach($c as $key => $value){ echo "<tr>"<td>company: $key</td><td>Table: $value </td></tr>"; } echo "</table>"; } else { echo "No Exhibitor data for the year $_POST[selectByYear]"; } I'm scraping a housing website with html source: Code: [Select] <tr><td> </td><td> Bedrooms </td><td> </td><td >3</td><td> </td></tr> <tr><td> </td><td> Full Baths </td><td> </td><td >1</td><td> </td></tr> <tr><td> </td><td> Partial Baths </td><td> </td><td >1</td><td> </td></tr> <tr><td> </td><td> Interior Sq Ft </td><td> </td><td >1,356</td><td> </td></tr> <tr><td> </td><td> Acres </td><td> </td><td >0.16</td><td> </td></tr> What i'm trying to do is create an associative array with only the details I want from the above. I've already got a function that steps through the HTML and creates an array element for each row with the contents of each <td> statement as follows: Code: [Select] $repl = array(" ", "(", ")"); $repl_with = array("", "", ""); foreach ($rows_feat as $id2 => $row2){ $features_raw = $scrape->fetchAllBetween('<td','</td>',$row2,true); //$features_data[str_replace($repl,$repl_with,strtolower(trim($features_raw[1])))] = trim($features_raw[3]); $countid=$countid+1; } The array produced by this would look like: features_raw[1] = Bedrooms features_raw[3] = 1 Basically, I want to take data like this: Beds 1 Baths 1 Garage Yes and create an array on the fly: House[beds]=1 House[baths]=1 House[garage]="yes" The problem is that the order of Beds, Baths and Garage changes. So on some house pages the order would be Baths, Garage, Beds.. etc. Any pointers out there? Thanks, Brett |