PHP - Dynamic Variable Array ?!
Hi !
I'd like to count all occurences in "$thiscodestring" into a "dynamic?" array and print it out after the end of the loop, how do I assign the variablenames dynamically ? $query = "SELECT codes, status FROM table"; while ($row = mysql_fetch_assoc($result)) { $thiscodestring = $row[codes]; // looks like "a1 c2 d3 10 15 1 a1 a1"; $singlecodes = explode(" ", $thiscodestring); foreach($singlecodes as $thiscode) { $$thiscode[count] = $$thiscode[count] + 1; } } After all Mysql-Stuff is done I'd like to print out the counted codes, for example the code "a1" was found 100 times in all querys then $$a1[count] should be 100, c2 was found 15 times, then $$c2[count] should be 15 and so on. Question: How do I tell php to assign a "dynamic" variable with the name of the found string which was exploded (in this example a1, c2, d3... ) before ?! $$ does not seem to work. And how can I then print_r() the value if I dont know the name ? Thanks ! Similar TutorialsHello all, I have yet again trouble finding a logical solution to my problem. I'm fetching an array which can hold 1 or more values. The problem is, I want these values to ouput in my json_encode function, but this also needs to happen dynamically depending on the amount of values. I can't explain it further, so here's the code so far: Code: (php) [Select] $files = mysql_fetch_array($get_files); $a = count($files); $i = 1; while ($files) { $variablename = 'fileName' . $i; $$variablename = $files['fileName']; $i++; } $output = array( OTHER VALUES , 'fileName1' => $fileName1, 'fileName2' => $fileName2, 'fileName3' => $fileName3, ............); // How do I add the fileNames dynamically depending on how many there are? This got me thinking, I also need to dynamically GET the values with jQuery. How would I do that, when the above eventually works? Thank you. Hello. I want to create some variables dynamically. I have this so far: for($i = 1; $i <= 4 ; $i++){ $a = 'member' . $i; $$a = array(); } Does that give me this 4 arrays?: $member1, $member2, $member3 and $member4? Of course I want some process inside of the loop, but that would depend on the variables. Would that work? thanks! <?php $foo = 5; $too = 7; ${"foo"}++; ${"too"}++; echo $foo; echo '<br />' . $too; $my_var_name = "foo"; ${$my_var_name}++; echo $foo; ?> I understand the part that $my_var_name is going to increment $foo. But I don't understand that when we used ${"foo"} we did not add the $ sign with it. But when we use ${$my_var_name} we have to add another $ sign. why is that? OK, what I am trying to do is generate a dynamic variable name. I want to setup a foreach statement that will generate variable names based on an array of data. $numbers = array('one', 'two', 'three', 'four', 'five', 'six', 'seven'); foreach ($numbers as $number) { } What I need, is for a bunch of variables to be generated and filled with content. $variable_one_label = "Blah"; $variable_two_label = "Blah Again"; How can I generate the dynamic variable based on the array value? I have a form that inserts information into a mysql, the only prolem is I need to add different surrounding html to the information when entering it into the database depending what the value is...(essentially I want to store font color around different levels) How would I define the same variable with different information depending on the value? The information is called using: if ($_SERVER['REQUEST_METHOD'] == 'POST') { $editLEVEL=$_POST['level']; I want it so if 'Level1' is the posted value then $editLEVEL would be '<color=1>$editLEVEL</color>' but if 'Level2' is the posted value the $editLEVEL would be '<color=2>$editLEVEL</color>' If you dont understand just let me know I'll try explain best I can. hi guys I just could not find the answer on forum. I have a url like this http://www.example.com/deal.php?id=367 and my question is : how can i use curl function to get the html and the id value which is 367 thanks Hi guys im in the middle of optimizing code.. Code: [Select] $sql = "SELECT * FROM sa_enemystats WHERE username='$username'"; $res = mysql_query($sql); while ($row = mysql_fetch_assoc($res)) { $enemy['current_health'] = $row['current_health']; $enemy['current_skill'] = $row['current_skill']; $enemy['level'] = $row['level']; $enemy['damage'] = $row['damage']; $enemy['evade'] = $row['evade']; $enemy['accuracy'] = $row['accuracy']; $enemy['speed'] = $row['speed']; $enemy['luck'] = $row['luck']; echo 'debug: variables synced with db table'; }I know that the setting of these variables are messy and can be done in a better way... but how? I have tried foreach and copying other's code for an array copy but it lead no where. Then again my syntax could be wrong... I used something like Code: [Select] foreach ( $enemy[$value] as $row => $value) { $enemy[$value] = $row[$value]; } Hello, I'm working on a dynamic text form (I guess thats what its called). Basically, I have a html page that echos in some PHP code. What the PHP code does is show different strings of text depending on a variable: Code: [Select] <PHP? $brief1_info = "brief info goes here"; $brief1 = 0; if (isset($_POST['brief1Go'])) { $brief1 = $brief1 + 1; } else if (isset($_POST['brief1Back'])) { $brief1 = $brief1 - 1; } $breif1Controller = " <form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\"> <input type=\"submit\" name=\"brief1Back\" id=\"brief1Back\" value=\"BACK\" /> </form> <form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\"> <input type=\"submit\" name=\"brief1Go\" id=\"brief1Go\" value=\"CONTINUE\" /> </form>"; if($brief1 == 0){ $brief1_info = "<b>Welcome Commander,</b> you are currently viewing the Mission Control Brief page, here you can view all your missions that you need to complete in order to advance through your prestiges. You will need to follow your briefs carefully in order to succeed. <br /><br /> "; } else if($brief1 == 1){ $brief1_info = "Okay, let me show you around the place ..."; } else if($brief1 == 2){ $brief1_info = "brief is on 2"; } ?> The problem is, the BACK and CONTINUE buttons don't work. If $brief1 equals 0, and the user presses continue, the is should go to 1, and the brief1_info string is changed (so some different text shows in my html). It actually works when brief1 is on '0', but when its on 1 and the user pressed continue, the brief1 is changed to 1, but because the submit button refreshes the page, the variable is re-read again, and thus is reset back to 0. Is there a way around this? Or is there a better method than what I'm doing? Thanks Hi I'm trying the following code: Code: [Select] $t = '12<-- AB_C -->'; $AB_C = 'abc'; echo preg_replace('/\<-- ([A-Z_]+) --\>/', "$$1", $t);I want to get "12abc" , but it outputs: 12$AB_C , so, it not recognize the replacement as dynamic variable. Is it any way to use the matched word in preg_replace() as a variable, or dynamic variable? Hi all, here's my code: Code: [Select] <?php foreach ($_SESSION['topping'] as $value) { echo "<tr><td width='30%'>Topping</td><td width='50%'>$value</td><td width='20%'><select name='notopping'>"; foreach ($_SESSION['cupcake'] as $number) { '<option name="notoppings[]" value="'.$number.'">".$number."</option>'; } echo "</select></td></tr>"; } ?> $_SESSION['cupcake'] is a value from either 6, 12, 24 or 36. What I want to do is put them into a drop down box (second foreach) as the value and the displayed value - counting up from 1 (so 1,2,3,4,5,6 or up to 12,24 etc). Also by creating this as an array, does this mean than for each topping (say Vanilla and Chocolate) the value dynamically created can be used on the next page by using $_POST['notoppings'] to display each type (two different numbers - one for Vanilla and one for Chocolate). Does that make sense? Thanks! Jason I need a help in the following : I have an admin page from where the admin attaches an gif image.This attached image should be shown to the user as a scrolling image. The code for the scrolling image is done through javascript. So my actual problem is getting the name of the attached gif image to the javascript array which is used for scrolling horizontally. hi all, I have an language pack for example: languages/en.php: Code: [Select] $en['mail']['letter closing'] = "regards,\n your friend!"; and in my config: Code: [Select] $language = "en"; $include_language = @include("languages/".$language.".php"); if(!($include_language)) { $try_default_language = @include("languages/nl.php"); if(!($try_default_language)) { echo "kan de taalpakket niet vinden<br>"; echo "Could not find the language pack.<br>"; echo "example on error: ".$test." shows nothing"; exit; } } In my function I want to include the language pack for example i have $language = 'en' so I want to include $en['general']['letter closing'] I will do this: Code: [Select] global $language,${$language}['general']; But that gives an error unexpected '[' blah blah. How can i call the variable variable array in the valid php way? 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 How can I use php to update a dynamic amount of input fields and tell mysql which ones to update respectively? Essentially I have a list of occupations and if someone wants to update one of them I don't know how to tell php which one they've changed in a dynamic way. Code: [Select] <?php if(!empty($occupations)) { ?> <h3 id="job_function">Job Functions</h3> <?php $i = 0; foreach($occupations as $occupation) { ?> <div class="formElement"> <div class="formFieldLabel "> <label for="occupation_<?php echo $i; ?>"><?php echo $occupation['companyname']; ?></label> </div> <div class="formField"> <input id="occupation_<?php echo $i; ?>" type="text" name="occupation_<?php echo $i; ?>" value="<?php echo $occupation['function']; ?>" /> </div> </div> <?php $i++; } } ?> Hi, Is there any way to pass dynamic arguments to array_multisort. Below is my idea of what the code should look like. First it has the data then its builds an array of array indexes with the sort direction. This array is then passed to the array_multisort function with the original data. Code: [Select] $data[] = array([0] => 67, [1] => 2, [3]' => 2001); $data[] = array([0] => 86, [1] => 4, [3]' => 2002); $data[] = array([0] => 98, [1] => 5, [3]' => 2002); $data[] = array([0] => 86, [1] => 6, [3]' => 2003); $data[] = array([0] => 67, [1] => 1, [3]' => 2004); $arg = array(1 => SORT_ASC, 3 => SORT_DESC); array_multisort($arg, $data); I have got this working with hardcoded values, for example... Code: [Select] array_multisort($sort1, SORT_ASC, $sort3, SORT_DESC, $data); but in my code instead of just 2 sorts there could be 'x' amounts. I hope ive made this clear. Any response would be much appreciated. Thanks in advance. Hi all. I am currently trying to build a site that will allow users to manage a self build house project. This is my first php MySQL project but I am getting to grips with it ok. I am currently building this for my own benefit at the moment as I am about to undertake a self build. I have a few questions to put to you guys. This is where I am at the moment I have a database table named materials which contains a list of materials , quantities, unit of measurement, id. My site has a user control panel that has separate forms for each stage of the build where the user enters the quantities of the materials, and the data is displayed as an array for each stage. So, heres question 1. I want to take the data and use it to generate a form which will be completed by several merchants.... so it will display similar to the array but will be a form with a text box for price where the merchant will insert a price. i.e <?php mysql_connect ("localhost", "test", "test") or die ('I cannot connect to the database becuase: ' . mysql_error()); mysql_select_db ("matquant"); // query $query = mysql_query("SELECT * FROM `quantites` ORDER BY `id` ASC"); // results while ($row = mysql_fetch_array($query)) { echo "<br />" .$row ['id']. " " .$row ['material']. " " .$row['quantity']. " " .$row['unit']. "<br />";} echo mysql_error(); ?> I want to add a text input box form which will allow the merchant to add a price to each item that is added to the array. so there the merchant will be able to give me a price for all the items in my list. Heres where I get stuck.... as I am constantly adding to the list I have no fixed amount of items so the form for the merchants needs to be built dynamically, ie each time I add a new material, I want the merchants form to get a new input. I am not very good at describing my problems but I am hoping that someone can help me out from the information given. Thats the first question. i like to get issues sorted in small bites. the second is the next big bite, I want to send the form above to several merchants, so I intend to have a user database with a user for each merchant, and link the tables so that each merchant can provide a price for each material, ideally the form would highlight the materials that have not had a price yet. I'm looking for advice on the best method of doing this basically but if I can get the first question sorted that would be great.. I have the test site local but can upload it it to the server if it will help you see what im trying to do. Any help that anyone can give will be greatly appreciated. In brief, I'm attempting to capture the form data from a dynamic form to a mysql database. From he
To He
The post data looks like this from the form - Array(
... ) PHP CODE:
... As a non-php or mysql developer, I'm learning on the fly. This is a section of the php file that I was using to post the form data to mySQL. This worked great up to the point I added the dynamic form widget. <?php // This function will run within each post array including multi-dimensional arrays function ExtendedAddslash(&$params) { foreach ($params as &$var) { // check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside. is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var); unset($var); } } // Initialize ExtendedAddslash() function for every $_POST variable ExtendedAddslash($_POST); $submission_id = $_POST['submission_id']; $formID =$_POST['formID']; $ip =$_POST['ip']; $fname =$_POST['fname']; $lname =$_POST['lname']; $spousename =$_POST['spousename']; $address =$_POST['address'][0]." ".$_POST['address'][1]." ".$_POST['address'][2]." ".$_POST['address'][3]." ".$_POST['address'][4]." ".$_POST['address'][5]; ... $db_host = 'localhost'; $db_username = 'xxxxx'; $db_password = 'xxxxx'; $db_name = 'xxxxx'; mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error()); mysql_select_db($db_name); // search submission ID $query = "SELECT * FROM `tableName` WHERE `submission_id` = '$submission_id'"; $sqlsearch = mysql_query($query); $resultcount = mysql_numrows($sqlsearch); if ($resultcount > 0) { mysql_query("UPDATE `tableName` SET `fname` = '$fname', `lname` = '$lname', `spousename` = '$spousename', `address` = '$address', WHERE `submission_id` = '$submission_id'") or die(mysql_error()); } else { mysql_query("INSERT INTO `tableName` (submission_id, formID, IP, fname, lname, spousename, address) VALUES ('$submission_id', '$formID', '$ip', '$fname', '$lname', '$spousename', '$address') ") or die(mysql_error()); } ?> It has been suggested that I explore using the PHP Explode() function. It's possible that may work, but can't get my head around how to apply the function to the PETLIST Array. Looking for suggestions or direction to find a solution for this challenge. Looking forward to any replies. Code: [Select] $word = 'numbers'; $numbers= array('1', '2', '3', '4'); echo $$word[0]; I expected the output to be '1'. It ended up being nothing... Why does this not work? Is it not possible to have a variable variable array? And if not, is there a workaround? Cheers, Joe hello all, I have an array value in my post array ($_POST['check0'] ) that I am trying to break up into php variables. For some reason if I do this: $var1 = $_POST['check0'][0]; all I get is the first letter of the string from the first value of the array? Hey, im struggeling with a small piece of code.... Thats my code: Global $user_ID; $user_ID = get_current_user_id(); echo"User number $user_ID is loggedin";
Echo gives me this:
Now i want to add it to my array: $atts['href'] .= $user_ID . 'abc'; 'href' is set to "https://test.com/" What im getting now ist https://test.com/abc
Can someone tell my why the '2' is missing??
|