PHP - Shuffle() An Array As An Element Of Root Array?
I'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]? Similar TutorialsOk I'm really lost here, what I need to do is shuffle a 2D array. Now when I shuffle them I want to keep both columns aligned to say. Like I only want the index to change. Kinda like this: Index Id URL 0 [2 www.e] I want the bracketed stuff to stay aligned. 1 [6 www.b] 2 [12 www.c] 3 [60 www.h] But I want them in different positions on every page load. So when I echo array[1][0] it will always be different. Is this even possible? Hi all, How do I get the following paths from the array separately in a foreach loop? level.dat level.dat_old session.lock uid.data If I use Code: [Select] foreach($outer_dir as $key=>$val) [code] then I get a warning because its returning the folder as 'Array'. The files still upload, as well as a single file called Array. Can i just strip these from the foreach? [code] Array ( [data] => Array ( ) [level.dat] => level.dat [level.dat_old] => level.dat_old [players] => Array ( [herghost.dat] => herghost.dat ) [region] => Array ( [r.-1.0.mcr] => r.-1.0.mcr [r.0.0.mcr] => r.0.0.mcr ) [session.lock] => session.lock [uid.dat] => uid.dat ) herghost.dat Many thanks from a confused user Hello, I'm trying to calculate the square root of X values in an array minus the average of the array, but the first half of the values are negative, so I'm using the abs(); function to change them to positives first, but I'm still getting "NAN" as the result for the negative values that 'should' be positive. $x = array(7,3,4,6,4,2,7); $sqrt = true; $x = sort($x); $mean = 4.71; // average $XminA = array(); foreach($x as $val) { ($sqrt == true) ? $XminA[] = round(sqrt(abs($val) - $mean),2) : $XminA[] = round($val - $mean,2); } echo "<pre>"; print_r($XminA); echo "</pre>"; and my result is... Quote [XminA] => Array ( => NAN [1] => NAN [2] => NAN [3] => NAN [4] => 1.14 [5] => 1.51 [6] => 1.51 ) Not sure what I'm doing wrong, any help is appreciated. Thank you! Kind Regards, Ace EDIT: stupid mistake, need it to the power of 2 not square root. Using the wrong function sorry: ($sqrt == true) ? $XminA[] = round(pow((abs($val) - $mean),2) : $XminA[] = round($val - $mean,2); // pow() not sqrt() Quote [XminA] => Array ( => 7.34 [1] => 2.92 [2] => 0.5 [3] => 0.5 [4] => 1.66 [5] => 5.24 [6] => 5.24 ) 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 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 } How would you access the number 10 in the $arr array? 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! 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. 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. 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. 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.] 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? 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 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 Folks, I am not able to find any function that will sort an array elements by its element's length. Does such function exist? |