PHP - Array Element In Each Cell
Similar TutorialsI'm creating a quick survey app for my son's cub scout pack's end-of-year surveys. There are two sets of questions: those where they want the responses to be completely anonymous and those questions where we need to know who filled out the response (people volunteering for positions, etc) I'm storing the responses in the db as two separate arrays, $anon and $nonAnon $anon[0] will be an array containing all the questions: $anon[0][0] = Survey question # 1 $anon[0][1] = Survey question #2, etc. The responses will be stored as arrays and placed in $anon as the 2nd element: $anon[1][0][0] = first response, answer to the first question $anon[1][0][1] = first resopnse, answer to the 2nd question $anon[1][1][0] = 2nd response, answer to the 1st question Etc. The pack leadership is concerned that no one would be able to reconstruct which anon response belonged to whom by matching up the order of the anon answers with the non-anon answers. Therefore I'd like to shuffle at least the anon responses. The long answer would be to build a temp array using the elements in $anon[1] and then shuffle that array and then reassign it to $anon[1]. Is there a way to use shuffle directly on $anon[1] without having to build a temporary array, shuffling it, then replacing the elements of $anon[1]? How would you access the number 10 in the $arr array? Given the following example code; if a function were passed the value of $id is there a way to point to the previous or next element in the array to retrieve their values. thanks Code: [Select] $arr = array(); for( $i = 0; $i < 10; $i++ ) { $id = mt_rand() + $i; $arr[$id] = "some value"; } function getValue( $id ) { $element = $arr[$id]; //point to previous element or next element beginning from $element position } Hi there! Ok I've a very simple code he $character = array (name=>"Joe", occupation=>"Programmer", age=>30, "Learned language "=>"Java" ); print_r($character); echo "<br/>"; foreach ( $character as $key=>$val ){ print "$key = $val <br>"; } The output is: Code: [Select] Array ( [name] => Joe [occupation] => Programmer [age] => 30 [Learned language ] => Java ) name = Joe occupation = Programmer age = 30 Learned language = Java Now instead of returning all the other elements, I just need to display only the first element in the array that is the value 'Joe'. I tried $val[name]; Output I get is not what I want: Code: [Select] J P J All responses/feedbacks is always welcomed Thank you! Hi, I have this array: $cats = array( "A"=>'Business Expansion Specialist', "B"=>'Affiliate Page', "C"=>'Personal: Hobbies', "D"=>'Personal: Pets', "E"=>'Personal: Holidays', "F"=>'Personal: Sport', "G"=>'Personal: C.V.', "H"=>'Personal: Other', "I"=>'For Sale: Antiques', "Z"=>'Other' );
And then from a table I get the variable $cat_cd. $cat_cd contains 'F' so it refers to 'Personal: Sport' If I want to put that in $category, how would I write that? I thought it might be .... $category = $cats['$cat_cd']; I tried that and it didn't work .
Thanks
Hi Everyone I am looking to just grab the first element of an array and do something to it but i only want this extra bit off code on the first value off the array. Here is my array echo "<pre>"; print_r($_SESSION); echo "</pre>"; Array ( [attach] => Array ( ) [backups-2] => true [dnb] => true [house] => true [tech-house] => true [uk-garage] => true [uk-grime] => true [uk-hip-hop] => true [uncategorized] => true [warehouse] => true [value] => Array ( [0] => Array ( [tune_name] => Music/dnb/Abort_Delta Heavy_192.mp3 [tune] => http://isdmusic.s3.amazonaws.com/Music/dnb/Abort_Delta Heavy_192.mp3 [submit] => Listen ) [1] => Array ( [tune_name] => Music/dnb/Acid Bath (Northern Lights remix)_Twisted Individual_192.mp3 [tune] => http://isdmusic.s3.amazonaws.com/Music/dnb/Acid Bath (Northern Lights remix)_Twisted Individual_192.mp3 [submit] => Listen ) [2] => Array ( [tune_name] => Music/dnb/Awkward_Inside Info_192.mp3 [tune] => http://isdmusic.s3.amazonaws.com/Music/dnb/Awkward_Inside Info_192.mp3 [submit] => Listen ) [3] => Array ( [tune_name] => Music/dnb/Awkward_Inside Info_192.mp3 [tune] => http://isdmusic.s3.amazonaws.com/Music/dnb/Awkward_Inside Info_192.mp3 [submit] => Listen ) ) ) so i just what to effect the first value what to and autostart to it??? Here is my code. session_start(); header("Content-type: text/xml"); $xml_output = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"; $xml_output .= '<playlist version="1" xmlns="http://xspf.org/ns/0/">\n'; $xml_output .= "<trackList>\n"; $xml_output .= "\t<track>\n"; $xml_output .= "\t\t<location>" . $_SESSION['value'][0]['tune_name'] . "</location>\n"; $xml_output .= "\t\t<creator>sdf</creator>\n"; $xml_output .= "\t\t<album>sdf</album>\n"; $xml_output .= "\t\t<title>" . $_SESSION['value'][0]['tune_name'] . "</title>\n"; $xml_output .= "\t\t<annotation>I love this song</annotation>\n"; $xml_output .= "\t\t<duration>32000</duration>\n"; $xml_output .= "\t\t<image>covers/smetana.jpg</image>\n"; $xml_output .= "\t\t<info></info>\n"; $xml_output .= "\t\t<link>" . $furl . "</link>\n"; $xml_output .= "\t</track>\n"; foreach ($_SESSION['value'] as $value) { $furl = "http://isdmusic.s3.amazonaws.com/".urlencode($value['tune_name']); if(preg_match("/\.mp3$/i", $furl)) { $xml_output .= "\t<track>\n"; $xml_output .= "\t\t<location>" . $furl . "</location>\n"; $xml_output .= "\t\t<creator>" . $value['tune_name'] . "</creator>\n"; $xml_output .= "\t\t<album>" . $value['tune_name'] . "</album>\n"; $xml_output .= "\t\t<title>" . $value['tune_name'] . "</title>\n"; $xml_output .= "\t\t<annotation>I love this song</annotation>\n"; $xml_output .= "\t\t<duration>32000</duration>\n"; $xml_output .= "\t\t<image>covers/smetana.jpg</image>\n"; $xml_output .= "\t\t<info></info>\n"; $xml_output .= "\t\t<link>" . $furl . "</link>\n"; $xml_output .= "\t</track>\n"; } } $xml_output .= "</trackList>"; echo $xml_output; Thanks I have a stdClass Object array with nested User arrays as a value that I would like to display in a table cell. I am struggling and have exhausted a lot of time. I am hoping to get a shove in the right direction if possible. The image below will show what I am trying to do.
$someArray = json_decode($token_result); foreach ($someArray as $key => $value) { $combined[] = "<tr><td>" . $value->customer . "</td><td>" . $value->city . '</td> <td>' . $value->state . "</td><td>" . $value->zipcode . '</td> <td>' . $value->totalUsers . "</td><td>" . $value->totalActiveUsers . "</td><td>" . $value->totalInActiveUsers . '</td><td> <a href="">' . $value->users . "</a></td></tr>"; } foreach ($combined as $value) { print $value; } Here is what my Array and Objects look like Array ( [0] => stdClass Object ( [customer] => SWSH [city] => Thomasville [state] => GA [zipcode] => 31792 [totalUsers] => 6 [totalActiveUsers] => 6 [totalInActiveUsers] => 0 [users] => Array ( [0] => stdClass Object ( [firstName] => xxx [lastName] => xxx [phoneNumber] => [userName] => cb_igwrth@xxx.com [createdBy] => [isActive] => 1 ) [1] => stdClass Object ( [firstName] => Dan [lastName] => Stewart [phoneNumber] => +11111111111 [userName] => dan.sxx@xxx.ga.gov [createdBy] => kwilliams@xxx.com [isActive] => 1 ) ) ) [1] => stdClass Object ( [customer] => xxxx [city] => Carver [state] => MA [zipcode] => 02330 [totalUsers] => 3 [totalActiveUsers] => 3 [totalInActiveUsers] => 0 [users] => Array ( [0] => stdClass Object ( [firstName] => Leo [lastName] => Furtado [phoneNumber] => 781-000-0000 [userName] => LFurtado@xxx.com [createdBy] => TConger@ccccc.com [isActive] => 1 ) ) ) ) Table is attached
Hello All, I have used a function to collect a users information from the database. This is then returned as an array. Using this returned array, I wish to pass it into another function. Here is the code: The array is created in the collect() function and needs to be passed to the ipn_data function Code: [Select] /* This script is responsible for handling all subscription payments. It will collect all information, insert data into the relevant databases and then forward the user to PayPal with the relevant transaction ID. On return, the IPN listener will deal with all account changes whilst the user is held in a queue. */ /* ------------------------------------- */ /* DATABASE CONFIGURATION */ /* ------------------------------------- */ include_once "../config/config.php"; /* ------------------------------------- */ /* COLLECT SESSION INFORMATION */ /* ------------------------------------- */ session_start(); $id = "100000002"; // ID of logged in user $next_year = date("Y-m-d", strtotime("+365 day", time())); //Date next year /* ------------------------------------- */ /* SET VARIABLES */ /* ------------------------------------- */ $reason = $_GET["reason"]; /* ----------------------------------------- */ /* COLLECT USERS INFORMATION FROM DATABASE */ /* ----------------------------------------- */ function collect($id) { //Select the subscriber from the database $query = "SELECT * FROM subscribers WHERE id='$id'"; $query = mysql_query($query); //Collect the subscribers first name, last name and email address while($row=mysql_fetch_array($query)) { $fname = $row["fname"]; $lname = $row["lname"]; $email = $row["email"]; } //Collate subscribers information into an array return array('fname' => "$fname", 'lname' => "$lname", 'email' => "$email"); } /* ----------------------------------------- */ /* CREATE TIMESTAMP OF CURRENT TIME */ /* ----------------------------------------- */ function mktimestamp() { //Set date variables $day = date("d"); $month = date("m"); $year = date("Y"); //Make timestamp return mktime(0, 0, 0, $month, $day, $year); } /* ----------------------------------------- */ /* INSERT USERS DATA INTO ipn_data */ /* ----------------------------------------- */ //Create random identifier $ident = rand("1", "10000"); function ipn_data($info, $reason, $timestamp) { //WANT THE ARRAY TO BE PASSED INTO HERE!! //I TRIED PASSING THE $info VARIABLE INTO THE FUNCTION, WHICH IS WHAT I ASSIGNED TO THE COLLECT FUNCTION LATER IN THE SCRIPT } /* ----------------------------------------- */ /* Get ID of inserted ipn_data row */ /* ----------------------------------------- */ function get_id($ident, $timestamp) { //Setup Query to find ID $query = "SELECT * FROM subscribers WHERE timestamp='$timestamp' AND identifier='$ident'"; //Run Query $query = mysql_query($query) or mysql_error(); //Using query find ID while($row=mysql_fetch_array($query)) { $ltj_txn_id = $row["id"]; } return $ltj_txn_id or mysql_error(); } /* ------------------------------------- */ /* SWITCH REASON */ /* ------------------------------------- */ switch($reason) { case "subscribe": break; case "renew": //Collect array from user information array function $info = collect($id); //Get timestamp from our mktimestamp function $timestamp = mktimestamp(); //Insert users data into ipn_data table $run_ipn = ipn_data($reason, $timestamp, $ident); //Collect ID of record just inserted $get_id = get_id($ident, $timestamp); echo "$run_ipn"; break; case "upgrade": break; default: break; } Any ideas? Hi, I have an array key whose value is a line of html in quotes, the problem is , I don't know how to do it. Lol. Any help greatly appreciated because the below code is generating an error in my editor. Thank you. Derek here is the line. Code: [Select] 'level_1'=>"<img src='<img src='sundragon_environments/ocean/ocean1_FRAME.jpg'/>'", EDIT: actually I managed to fix the error adding a semicolon after the parenthesis. Is this array correct please? Code: [Select] $currentLocation = array ( 'teardrop_ocean_bg' => array ( 'level_1'=>"<img src='<img src='sundragon_environments/ocean/ocean1_FRAME.jpg'/>'" ) ); it's not finished yet. I am using session variables to keep track of what is in a shopping cart. I can add the items to the cart quite easily enough. But my problem is that I can't delete a specific item in the cart. Below is a summary of what the array looks like $Item1=array("ProdID"=>"Hat","Color"=>"Not Needed","Size"=>5); $Item4=array("ProdID"=>"Shirt","Color"=>"Green","Size"=>"L"); $Item2=array("ProdID"=>"Pants","Color"=>"Not Needed","Size"=>"32x32"); $Item3=array("ProdID"=>"Socks","Color"=>"Not Needed","Size"=>"Not Needed"); $NumItems=4; $TestArray=array("NumItems"=>$NumItems,1=>$Item1,2=>$Item2,3=>$Item3,4=>$Item4); However when I attempt to delete any of the top level elements (1,2,3,4,NumItems), I either end up deleting only the last element (4) or somehow taking out 2 of them. I know that this must be an easy fix but I've looked at it for so long that I can't seem to figure out what the problem is. below is the code that I use to delete the Item from the array Code: [Select] $ItemNum=$_GET['item']; if ($ItemNum=="All"){ $ItemNum=$_GET['item']; if ($ItemNum=="All"){ unset($TestArray); unset($TestArray['NumItems']); unset($_SESSION['OrderTotal']); //header("Location:Cart.php?act=view"); } else{ $TestArray['NumItems']=$TestArray['NumItems']-1; if($TestArray['NumItems']<1) { unset($_SESSION['OrderTotal']); unset($TestArray); unset($TestArray['NumItems']); } else { unset($TestArray[$ItemNum]); } Can anyone take a look at this and point me in the correct direction? What I am after is to delete any element of the top array and keep the rest. I am trying to break down an array to make it easier to read. An array that looks like Array (
=> 0 [1] => 0 [2] => 0 [3] => 0012844 1 [4] => 37 [5] => 1 etc...) I want to display it like:
Code: [Select] [0] => 0 [1] => 0 [2] => 0 etc... how can this be accomplished. 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 all, Is there a function or method to delete element from current position in array without knowing the index. For example: $ar = array( 1, 2, 3, "test", 4, 5, "test2" ); while( $v = current( $ar ) ) { if( key( $ar ) == "test" ) { // remove element from the array where key equals "test" // i could count every cycle and splice from that index but i wonder can that be done without it // i am looking at the php array functions but i can't find any that will delete from element from current position in array echo 'key( $ar ) je test. key( $ar ): ' . key( $ar ); } next( $ar ); } One thing that i don't understand is that when i run example above the "test" key is found and when i echo it it gives me 0. i am trying to check if the array element (which would be a file) is null or not. when i run it, uploading one file, it says "Please select some files to upload first!" X 3. what am i doing wrong? my code: http://pastebin.com/m0k3fEd2 I'm wondering if this is at all possible:- Code: [Select] $i = 7; $row_item['comment$i_name'] = "john"; with the $i in $row_item['item$i_id'] being replaced with whatever $i is set as sort of like this:- $row_item['comment.'$i'._name'] Is this sort of concatenation possible inside array element names as I can't seem to get it to work? Hi I am trying to modify my database and am using the following part of code which isn't working. $bad is various values seperated by a newline. The strange thing about the code is that it works when their is only one $value but won't work if their are two or more values even though it is too easy to be wrong. Please help $badarray=explode(array("\r\n", "\r", "\n"),$bad); foreach($badarray as $value){ $value= str_replace(array("\r\n", "\r", "\n"),NULL,trim($value)); echo $value; $query="Update googlevacancies_junk SET exist='$no' WHERE email='$value' "; mysql_query($query); } Is there any limit to the length of an array element in a flat data file? For instance, I have a flat file that I might end up having 200 rows, with each row containing 15 elements. Most of the elements will be about 20 characters or less, but a couple of the elements might be 300-400 characters. I'm guessing there is no limit. And since each row will be longer than one "line" in a .txt file, how best to mark the end of a row? [I assume that using a database is probably the better way to do this, but on this particular website I'm working on that isn't an option.] Folks, I am not able to find any function that will sort an array elements by its element's length. Does such function exist? I have a user table that holds email addresses and for testing purposes I am trying to replace every email address with an email address defined in an array. I would like to randomly choose an email address from the array and update the table with this address. When I run the following code it randomly chooses a email address from the array but then updates every row with this one email address. Can you someone please let me know what I am doing wrong. Thanks in advance. Code: [Select] $query = "SELECT * FROM user '"; $result = mysql_query($query); $input = array('email1', 'email2', 'email3', 'email4', 'email5', 'email6', 'email7'); $rand_keys = array_rand($input, 2); $replaceStr = $input[$rand_keys[0]]; while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $rand_keys = ""; $rand_keys = array_rand($input, 2); $replaceStr = $input[$rand_keys[0]]; mysql_query("UPDATE user SET email = '$replaceStr'"); } I have learned php coding by doing (looking for patterns and trying things) and I have hit a roadblock trying to modify a template that creates a delimited text file of products from an ecommerce site (Sunshop) for upload to google base. I have tried to search for the answer but I don't know what I don't know so I may not have put the right search terms in. So I apologize if this has been addressed in the past. The script uses case to call up the contents of specific rows of the product table which I understand but in when I want to call up the manufacturer row Sunshop uses a reference number and then a different table called manufacturers with an ID row that matches the manufacturer row numbers (that are associated with each product) and then next to it a name row which contains the actual manuracturer names. Can I put code in the case that will pull up the referenced name as opposed to just the numbers that are in the column? This is what I have now that just calls up the cells from the manufacurer row: Code: [Select] case 'mfg': $item[mfg] = $item[manufacturer]; The mfg refers to this part of the code in an array: Code: [Select] array('header' => 'manufacturer', 'value' => 'mfg'), In case it helps I will attach the full document. Thanks. |