PHP - Need Help With Complex Form And Arrays
I am so over my head right now that I don't even know where to begin asking for help?!
(This is regarding a Form which ask 10 Questions and then captures and processed up to 10 Answers.) Originally, I had an answerArray where I captured and process all User Answers to Questions, and all was beautiful in the universe! Then after being 95% done, I got the - not so brilliant - idea of dynamically generating my Q&A Form with Questions being pulled from the question table (along with Answers from the answer table). Based on a recommendation from gizmola (??), I created a SECOND Question & Answer multidimensional array - thoughtsArray - which pulled together the Questions and Answers. This made sense, because it is easier to populate the Form when the dataset is coming all from one place. The problem is two-fold at this point... 1.) Is it a good or bad design to have answerArray to capture and process Form inputs, and then a thoughtsArray for display purposes?? 2.) How do I design a Form which allows both my multidimensional thoughtsArray and my one-dimesnional answerArray to plug into it, specifically the name attribute?? Here was my original array... foreach($_POST['answerArray'] as $q => $a){ // Copy data from POST to PHP array. $answerArray[$q] = trim($a); if (strlen($answerArray[$q]) > 1024){ // Invalid Answer. $errors[$q] = 'Answer cannot exceed 1024 characters.'; } }//End of VALIDATE FORM DATA And here is my new display array... // Populate PHP array with Questions & Answers. $x=1; while (mysqli_stmt_fetch($stmt7)){ $thoughtsArray[$x] = array('questionID' => $questionID, 'questionText' => $questionText, 'answerText' => $answerText); $x=$x+1; } Here is how my original - pre automation - Form looked... <!-- Question 1 --> <label for="question1">1.) Why did you decide to start your own business?</label> <textarea id="question1" name="answerArray[1]" cols="60" rows="2"><?php if (isset($answerArray[1])){echo htmlentities($answerArray[1], ENT_QUOTES);} ?></textarea> <?php if (!empty($errors[1])){ echo '<br /><span class="error">' . $errors[1] . '</span>'; } ?> And here is my new Form - which works for displaying, but is now broken for processing... <?php foreach($thoughtsArray as $questionNo => $qaArray){ // Build Question. echo '<label for="question' . $questionNo . '">' . $questionNo . '.) ' . $qaArray['questionText'] . "\n"; // Build Answer. echo '<textarea id="question' . $questionNo . '" name="' . $qaArray["questionID"] . '" cols="60" rows="2">'; echo (isset($questionNo) ? htmlentities($qaArray['answerText'], ENT_QUOTES) : ''); echo "</textarea>\n\n"; } ?> Hope that all makes sense?! Debbie Similar TutorialsHey, So I'm doing a school assignment and my professor wants us to use an array to display forms and I have no idea how to do that.
He wants us to create an array of arrays like this: display_form( array( "type" => "text", "name" => "first_name", "value" => "", "label" => "First Name" ), array( "type" => "text", "name" => "last_name", "value" => "", "label" => "Last Name" ), array( "type" => "email", "name" => "email", "value" => "", "label" => "Email" ), array( "type" => "number", "name" => "extension", "value" => "", "label" => "Extension" ) ); But I dont understand how you use that array to actually display the form. Does anyone know how? This is really cool if I can get it to work My PHP CODE: Code: [Select] $ids = implode (",", $ibforums->input['checkbox']); Grabs from this data in my HTML FORM: Code: [Select] <input name="checkbox[]" type="checkbox" value="{$r['id']},{$r['friendid']}"> Now when I pass my input, I will get 2 different values in both array's how do I separate them out? I know how to seperate them out using implode, but I need to seperate BOTH of the array's that are being passed, and I need to use them separately. Hi there I am trying to send an array of items to delete from a form, receive them back to the page then enter them into another form and then send them back to the page. Basically its a delete then confirm delete thing. So I can send the array from the first form though I am not sure how to place them into the second (confirm delete) form. What I've got so far considering the array does get sent in the first place is First I receive the array: if (isset($_POST['delete'])) { if (isset($_POST['todelete'])){ $todelete[] = ($_POST['todelete']);////here is my problem I think echo <<<_END <div>Are you sure you wish to make these changes</div> <div><form action="" method="post"> <input type='hidden' name='todelete'value="$todelete"/> <input type='hidden' name='confirm'value="confirm"/> <input id='inputform' type='submit' size='50' value='Yes' /> </form> <form action="" method="post"> <input type='hidden' name='rollback'value='rollback' /> <input id='inputform' type='submit' size='50' value='No' /> </form></div> _END; } } Then I try and receive the array back with if (isset($_POST['confirm'])){ foreach ($_POST['todelete'] as $delete_id) { $query ="DELETE FROM gallery WHERE id = $delete_id"; $result=mysql_query($query) or die("Invalid Query : ".mysql_error()); echo "Removing Data"; } } What I receive is a warning: 'Warning: Invalid argument supplied for foreach() in C:\wamp\www\css\enterphotos.php on line 91" I am sure that there is a simple solution! Can anyone help me here? In my form I have this: Code: [Select] <div class="confSub {conferences.confClass}"> <div> <input type="hidden" name="confPK" value="{conferences.confPK}"> <label>Conference Attended:</label><input size="85" name="conference[{conferences.confCounter}]" type="text" value="{conferences.conference}"/> <label>Date:</label><input size="20" name="confDate[{conferences.confCounter}]" type="text" value="{conferences.confDate}"/> <span class="example left"> ( YYYY-MM-DD )</span> <label class="fullLabel clearfix">Description and Benefit to the University:</label> <textarea name="confDesc[{conferences.confCounter}]" cols="90" rows="5">{conferences.confDesc}</textarea> <input class="checkbox clearfix" name="confPres[{conferences.confCounter}]" value="yes" type="checkbox" {conferences.checkedConf}/> <label class="midLabel">Conference Presentation?</label> <label class="clearfix">Title of Presentation:</label> <input class="pushLeft" size="85" name="confPresTitle[{conferences.confCounter}]" type="text" value="{conferences.ConfPresTitle}"/> </div> </div> I need to take the values of the same index for eachof five arrays ($_POST['conference'], $_POST['confDate'], $_POST['confDesc'], etc...) and insert/update them into a mysql table. So conference[0], confDate[0], confDesc[0], confPres[0], and confPresTitle[0] all need to go into the same index of their respective fields in the DB table. If it was one array I could just do something like: foreach($_POST['conference'] as $conference) { // Update Conference $degreeQuery = "UPDATE CONFERENCES SET Conference = '".$conference."', StaffPK1 = '".$getPK1."' WHERE ConferencePK1 ='".$confID."'"; $degreeQuery = mysql_query($degreeQuery); } I'm having trouble with how to add a value from each array into the sql table. I could do it through a different foreach loop for each array and iterate through all foreach loops with another loop, but that doesn't seem very efficient. I'd like to do it with one sql statement for each set of "conference" data. Thanks in advance, Shannon Hi, I have an HTML and a PHP script inserting data into DB. My problem is when i submit the form, one of the arrays cannot be posted to my PHP Script. The first SELECT-OPTION Values (mail_select[]) are being posted correctly, however the second SELECT-OPTION Values (OS[]) are not. It brings empty value at all. If i put OS[] SELECT TAG to first place, -i mean put it before mail_select[] SELECT TAG-, this time mail_select[] brings nothing. And OS[] is being posted correctly. What could the possible problems be? Here is the HTML: Code: [Select] bla..bla.. <html> <form id="SK" action="post.php" method="POST"> <tr> <td> <?php $conn = getConn(); mysql_select_db(getDBName(),$conn); $query = "select MEMBERS,NAME from mail;"; $result = mysql_query($query,$conn); echo "<form>"; echo "<select name=\"mail_select[]\" id=\"mail_select[]\" multiple=\"multiple\">"; while($row = mysql_fetch_array($result)) { $NAME = $row['NAME ']; $MEMBERS = $row['MEMBERS']; echo "<option value='$MEMBERS'>$NAME</option>"; } echo "</select></form>"; mysql_close($conn); ?> </td> </tr> <tr><td> <?php $conn = getConn(); mysql_select_db(getDBName(),$conn); $query = "select mark from olsystem;"; $result = mysql_query($query,$conn); echo "<form style=\"margin:20px 0\">"; echo "<select name=\"OS[]\" id=\"OS[]\" multiple=\"multiple\">"; while($row = mysql_fetch_array($result)) { $isim = $row['mark']; echo "<option value='$mark'>$mark</option>"; } echo "</select></form>"; mysql_close($conn); ?> </td> </tr> <tr height="40"><td width="170"><div class="rowElem"><input type="submit" value="GO!" /><input type="reset" value="Clear" /></div></td></tr> </form> </html> Here is my PHP script: Code: [Select] <?php include("DB.php"); if(isset($_POST['OS'])){ $OS = implode(",",$_POST['OS']); $mail_select = implode(",",$_POST['mail_select']); register($OS,$mail_select); } function register($OS,$mail_select) { $conn = getConn(); mysql_select_db(getDBName(),$conn); $query ="insert into outage(OS,mail_select) values ('$OS','$mail_select')"; mysql_query($query,$conn); if(mysql_affected_rows()>0){ BLA BLA } else { } mysql_close($conn); } ?> I have this thing that i am trying to make but i cant get it to work.. can anyone help? Code: [Select] function sql_read( $dbname,$dbusername,$dbpassword ) { $names = array(); $password = array(); $connect = @mysql_connect("mysql11.000webhost.com",$dbusername,$dbpassword) or die("Could Not Connect"); @mysql_select_db ($dbname) or die("Could not find DataBase"); $query = mysql_query("select * from users"); $numrows = mysql_num_rows($query); if ($numrows > 0){ while($row = mysql_fetch_assoc($query)){ $names[] = $row["uname"]; $password[] = $row["password"]; $id = $row["id"]; } $return = array($names,$password,$id); }else{ $return = array(); } return $return[]; } $names = array(); $names = sql_read("XXXXXX","XXXXXX","XXXXXXX")[0]; The error i get is Code: [Select] Parse error: syntax error, unexpected '[' in /home/a5480952/public_html/sql/index.php on line 28 Line 28 is "$names = sql_read("XXXXXX","XXXXXX","XXXXXXX")[0];" Please help... i REALLLLD need help with this.. ask questions if you want to know more about what i am trying to do... thanks! I'm having troubling with trying to create a function to spit out a single array with the following array. I can write it in a away that looks through the arrays manually. the results i am trying to generate is that each item in generated array. Array to convert array( "account" => array( "login", "register", "logout", "edit", ), "p" => array( "report", ), "array1.0" => array( "array2.0" => array( "array3.0", "array3.1 ), "array2.1", ), generating the array will look like this
Array ( [0] => account [1] => account/login [2] => account/register [3] => account/logout [4] => account/edit [5] => p [6] => p/report [7] => array1.0 [8] => array1.0/array2.0 [9] => array1.0/array2.0/array3.0 [10] => array1.0/array2.0/array3.1 [11] => array1.0/array2.1 ) The idea is that id generates a single array with combined labels and arrays inside, etc. I just can't figure out how to create a script that will create this array even If I add a new value or array.
Hi everyone, I'm still kind of a noob when it comes to PHP although i am learning more when i can. I'm in the middle of creating an affiliate system in PHP/MySQL and as you'll be able to tell from looking at my code I'm no expert in it and no doubt what I've created can be done in a more efficient way. This is where i need your help, for 2 different reasons, one to guide/help me re-create my script the way you would do so. The second thing i need help with is (EDIT: i think we'll concentrate on re-creating the script first of all). //BEGIN GETTING BRAND NAMES $connection = mysqli_connect( "$connectip", "$swiftuser", "$swiftpass", "$swiftdb" )or die( "Error " . mysqli_error( $connection ) ); $sql = "SELECT Name, ProgramID FROM programs WHERE Status='1'"; $result = mysqli_query( $connection, $sql )or die( "Error in Selecting " . mysqli_error( $connection ) ); if ( $result->num_rows > 0 ) { while ( $row = $result->fetch_assoc() ) { $ProgramID = $row[ "ProgramID" ]; //BEGIN GETTING CLICKS THAT MONTH FOR THE BRAND $startmonth = date( 'Y-m-d', strtotime( 'first day of this month' ) ); $endmonth = date( 'Y-m-d', strtotime( 'last day of this month' ) ); $todaysdate = date( 'Y-m-d' ); $sqlclicks = "SELECT COUNT(*) AS 'TotalMonth' FROM `clicks` WHERE AffID = '$AffID' AND ProgramID = '$ProgramID' AND DATE(Timestamp) BETWEEN '$startmonth' AND '$endmonth' "; //echo $sqlclicks; $resultclicks = mysqli_query( $connection, $sqlclicks )or die( "Error in Selecting " . mysqli_error( $connection ) ); if ( $resultclicks->num_rows > 0 ) { while ( $rowclicks = $resultclicks->fetch_assoc() ) { $clicks = $rowclicks[ "TotalMonth" ]; } } else { $clicks = "0"; } //END GETTING CLICKS THAT MONTH FOR THE BRAND //BEGIN GETTING REGISTRATIONS THAT MONTH FOR THE BRAND $sqlreg = "SELECT COUNT(*) AS 'TotalReg' FROM `players` WHERE AffID = '$AffID' AND ProgramID = '$ProgramID' AND DATE(SignupDate) BETWEEN '$startmonth' AND '$endmonth' "; //echo $sqlclicks; $resultreg = mysqli_query( $connection, $sqlreg )or die( "Error in Selecting " . mysqli_error( $connection ) ); if ( $resultreg->num_rows > 0 ) { while ( $rowreg = $resultreg->fetch_assoc() ) { $reg = $rowreg[ "TotalReg" ]; } } else { $reg = "0"; } //END GETTING REGISTRATIONS THAT MONTH FOR THE BRAND //BEGIN GETTING FTDs THAT MONTH FOR THE BRAND $sqlftd = "SELECT COUNT(*) AS 'TotalFTDs' FROM `players` WHERE AffID = '$AffID' AND ProgramID = '$ProgramID' AND FTDmatched ='1' AND DATE(FTDmatchedDate) BETWEEN '$startmonth' AND '$endmonth' "; //echo $sqlftd; $resultftd = mysqli_query( $connection, $sqlftd )or die( "Error in Selecting " . mysqli_error( $connection ) ); if ( $resultftd->num_rows > 0 ) { while ( $rowftd = $resultftd->fetch_assoc() ) { $ftds = $rowftd[ "TotalFTDs" ]; } } else { $ftds = "0"; } //END GETTING FTDs THAT MONTH FOR THE BRAND //BEGIN CPA COMMISSION THAT MONTH FOR THE BRAND $sqldeal = "SELECT DealID AS `DealID`, SUM(CASE WHEN FTDmatched = '1' THEN 1 ELSE 0 END) AS `TotalFTDs` FROM players WHERE AffID = '$AffID' AND ProgramID = '$ProgramID' AND `FTDmatchedDate` BETWEEN '$startmonth' AND '$endmonth' GROUP BY DealID"; //echo $sqldeal; $resultdeal = mysqli_query( $connection, $sqldeal )or die( "Error in Selecting " . mysqli_error( $connection ) ); $dealid = array(); $dealftds = array(); $i = 0; if ( $resultdeal->num_rows > 0 ) { while ( $rowdeal = $resultdeal->fetch_assoc() ) { $dealid[ $i ] = $rowdeal[ "DealID" ]; $dealftds[ $i ] = $rowdeal[ "TotalFTDs" ]; $i = $i + 1; } } else { $commissionftd = "0.00"; } $totaldeals = count( $dealid ); //echo "<br>"; //echo "Total Deals for Affilaite is: " . $totaldeals; $sqlpayout = array(); $totalcpa = array(); for ( $tt = 0; $tt < count( $dealid ); $tt++ ) { $sqlamount = "SELECT CPA AS `CPAAmount` FROM affDeals WHERE AffID = '$AffID' AND `affDealID` = '$dealid[$tt]' AND `Type` = 'CPA' AND `StartDate` <= '$todaysdate' AND `EndDate` >= '$todaysdate' OR AffID = '$AffID' AND `affDealID` = '$dealid[$tt]' AND `Type` = 'Hybrid' AND `StartDate` <= '$todaysdate' AND `EndDate` >= '$todaysdate'"; //echo "<br>" . $sqlamount . "<br>"; $resultamount = mysqli_query( $connection, $sqlamount )or die( "Error in Selecting " . mysqli_error( $connection ) ); if ( $resultamount->num_rows > 0 ) { while ( $rowamount = $resultamount->fetch_assoc() ) { $sqlpayout[ $tt ] = $rowamount[ "CPAAmount" ]; $totalcpa[ $tt ] = $sqlpayout[ $tt ] * $dealftds[ $tt ]; } } else { $sqlpayout[ $tt ] = "0.00"; } } //END CPA COMMISSION THAT MONTH FOR THE BRAND $totalcommission = array_sum( $totalcpa ); echo '<tr> <td>' . $row[ "Name" ] . '</td> <td>' . $clicks . '</td> <td>' . $reg . '</td> <td>' . $ftds . '</td> <td>£' . $totalcommission . '</td> </tr>'; } } else { echo "0 results"; } //END GETTING BRAND NAMES ?> I've also attached the SQL tables, the table Affiliates is just the structure so you will need to add a record in there. All other tables have data in them for you to work with. EDIT: since i cant upload SQL files on here you can download them he https://ufile.io/gnoqf I find it a lot easier for me to learn PHP by trying to create stuff myself, then if i need help i do some research on how to achieve what I'm trying to code and if i fail i keep trying to doing more research until it works. I also ask other PHP developers for advice and help and if they provide me with examples then again that helps me learn a lot better and quicker as i can see first hand how its supposed to look and how it works. I apologise for my messy coding but like i said I'm still learning PHP, if anyone could help me re-create my script more efficiently I'd very much appreciate that. Maybe I've done too much code and certain MySQL queries can be done in just 1 MySQL Query instead of multiple ones, i don't know and that's why I'm here asking for help/advice to help me learn more. Anyway thank you in advance and if you'd like to know any information please let me know. Well, as i said in my previous post, im pretty new into php, mysql, i was searching into how to make queries but i can't find where to learn doing real complex ones. This is how it goes, -i've got an array full of id's -inside my table i wan't to get all the values where folder_id == to any id inside my array(i guess a loop would do this) -and i wan't to get only the first 20 values of the columns (folder_id and photo) for every folder_id any suggestions? thanks Greetings - So I have an issue with my form right now which can be found he http://youawfulme.com/Form.html If you look, you will see two expanding columns under Providers and References. The HTML code for them to expand looks like this: Quote <span class="duplicateSpan"><a id="tfa_0583059728034-wfDL" class="duplicateLink" href="#">Next Provider</a></span> and the PHP code that handles their database storage looks like this: Quote // Insert Providers.. if(count($_POST['tfa_FirstName1']) > 1) { for($i = 0; $i < count($_POST['tfa_FirstName1']); $i++) { $tmpsql = "INSERT INTO tmpProviders (tmpId,FirstName,LastName,LicenseType,PrimarySpecialty,SecondarySpecialty,NYStateLicenseNum,DEANumber,NPINumber,EmailAddress,DaysPerWeek,PrimaryCareProv) VALUES ($oldid,'" . $_POST['tfa_FirstName1'][$i] . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_LastName1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_LicenseType1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_PrimarySpecialty1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_SecondarySpecial'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_NYStateLicenseNu1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_DEANumber1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_NPINumber1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_EmailAddress1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_DaysPerWeek1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d+/","\\1",$_POST['tfa_Ifthisindividual'][$i]) . "');"; mysql_query($tmpsql); } } else { $tmpsql = "INSERT INTO tmpProviders (tmpId,FirstName,LastName,LicenseType,PrimarySpecialty,SecondarySpecialty,NYStateLicenseNum,DEANumber,NPINumber,EmailAddress,DaysPerWeek,PrimaryCareProv) VALUES ($oldid,'" . $_POST['tfa_FirstName1'] . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_LastName1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_LicenseType1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_PrimarySpecialty1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_SecondarySpecial']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_NYStateLicenseNu1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_DEANumber1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_NPINumber1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_EmailAddress1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_DaysPerWeek1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d+/","\\1",$_POST['tfa_Ifthisindividual']) . "');"; mysql_query($tmpsql); } if(count($_POST['tfa_PracticeName']) > 1) { At this moment, when you fill out my form, all of the information saves to three separate tables. The Provider input goes into a temporary providers table, the Referrals to a temporary Referral , and the rest of the data to a temporary information table. Once the user submits the application, the temporary tables are cleared after having been moved to permanent tables (Still three tables) My goal is for all of these values to save to one table, whether it be from three separate temps to one final or one temp to one final. My programmer was having trouble figuring it out and kind of left me on my own.. I really need some help The Providers and Reference tables are done in such a way that if there are more than one entry, it will create a new row for each entry with a new ID number but the same "tempid" number, the latter matching the ID number in the main information table. Can I have it such that PHP will check to see if the tempIDs match, and if they do, move the information into new columns on the same row? So that way, instead of having say 3 different IDs with one temp ID for three different providers.. instead have that information all placed on one row, with one ID, and new columns? In my head, I figured I would expand my table 5x. If I have five columns now, I will have 25 after. For each "Provider Name", I will now have "Second Provider Name", "Third Provider" name, etc... If the user only adds one provider, these won't be used. If they had multiples, up to five, the info will be placed into these new columns. I just can't get this to work.. When I expand the column and inspect the element in HTML, it says, for example, Provider[1] and Provider[2] .. Incrementing in brackets for each addition. But if I try to, say Quote $SecondProviderName = $_POST['tfa_ProviderName[2]']; .. It simply doesn't work. Sorry for all this, I just need some help and so far you guys have been a great resource. Thank you This is the array Array (2) ( | ['0'] => Array (6) | ( | | ['name'] = String(7) "Pikemen" | | ['hp'] = Integer(3) 100 | | ['atk'] = Integer(1) 5 | | ['def'] = Integer(1) 5 | | ['rng'] = Integer(2) 15 | | ['amt'] = Integer(2) 30 | ) | ['1'] => Array (6) | ( | | ['name'] = String(8) "Champion" | | ['hp'] = Integer(3) 150 | | ['atk'] = Integer(1) 8 | | ['def'] = Integer(1) 6 | | ['rng'] = Integer(1) 5 | | ['amt'] = Integer(2) 10 | ) ) I have an attack value ( say 300 ). I want to take this value and minus the first key amount $array[0]['amt']. If that value then comes to 0 I then want to skip to the next array key and do the same $array[1]['amt'] until the attack value runs out or every array keys amount is equal to 0. Any ideas? Hi,
Is it possible to create an web-page,form,that would accept specific input and generate Xojo or Php for this could be used, below is the sample XML file and Data Format.
<?xml version="1.0" encoding="UTF-8" ?>
If Yes, then how to write the desired PHP code to solve this problem?
Thanks Hi; i would like to search for a regular expression to grab all printf occurences including the folowing senarios :
printf("something"); printf("something", variables); printf("something", variables, variables); printf("something);something", variables, variables);To simplify the third and fourth cases, the regex should start from printf(" and go intil it find ); with a white space after it. But i didn't realise how to do it. This trick should work also for the first and second case. Thanks Edited by Dareros, 26 September 2014 - 01:27 PM. Hey. I am not 100% with it at the moment, bit under the weather. (If you ask why I am working, your not a developer) Sob story aside (excuses really) Basically I have built a function to manipulate BB Code to HTM I wrote it, looked back at it and thought, my god this looks overly complex for this sort of thing. It works but just seems like a lot of wasted code. Please help me narrow this down public function BB2HTM($str){ /* Valid BB Code [b] / [/b] = STRONG [i] / [/i] = Italic [u] / [/u] = Underline [url=http://www.example.com]My Example[/url] = A Link [size=X]bla[/size] = Change font size where X is percentage of actual size, default options 50=>small, 100=>normal, 200->large [list]bla[/list] Handles Unordered Lists, with New Line being new list item [list=X]bla[/list] Handles Ordered List, where X is start number, again New Line is New List item */ /* First, we will do the basics, with a simple str_replace */ $str = nl2br($str); $arrBBCode = array('[b]', '[/b]', '[i]', '[/i]', '[u]', '[/u]'); $arrHTMCode = array('<strong>', '</strong>', '<i>', '</i>', '<u>', '</u>'); $str = str_replace($arrBBCode, $arrHTMCode, $str); // /* Now we want to handle a URL, open in new window */ $regexURLPattern = '#(\[url\=(.*))(\])(.*?)(\[/url\])#is'; preg_match_all($regexURLPattern, $str, $arrMatches); /* Loop through the results, build a valid HTM link and replace what we found with the correct format */ for($i = 0; $i < count($arrMatches[0]); $i++){ $strNewLink = '<a href="'.$arrMatches[2][$i].'" target="_blank">'.$arrMatches[4][$i].'</a>'; $str = str_replace($arrMatches[0][$i], $strNewLink, $str); } /* End Handle URL */ /* Now font size. User can maniplate the number on size so we want to check for this and limit, so someone dont put 1% and hide stuff or 10000% and break the website */ $regexSizePattarn = '#(\[size=)([0-9]*)(\])#'; preg_match_all($regexSizePattarn, $str, $arrMatches); /* Loop through the results, put a check on the number */ for($i=0; $i < count($arrMatches[0]); $i++){ if($arrMatches[2][$i] > 200){ $arrMatches[2][$i] = 200; }elseif($arrMatches[2][$i] < 100){ $arrMatches[2][$i] = 100; } /* Change it and close the tag, keep the str_replace with the opener for later editing / auditing */ $strFontTag = '<span style="font-size:'.$arrMatches[2][$i].'%">'; $str = str_replace($arrMatches[0][$i], $strFontTag, $str); } $str = str_replace('[/size]', '</span>', $str); /* End Handle Size */ /* Is it a list, What list, where to start */ $regexListPattern = '#(\[list)(=?)([0-9]*)?(\])(.*?)(\[/list\])#is'; preg_match_all($regexListPattern, $str, $arrMatches); /* Loop through our results */ for($i = 0; $i < count($arrMatches[0]); $i++){ $strLstItems = ''; /* Is it unordered or Ordered? Where do we start, 1 or 100 Add our closing tag here as well in variable, save doing this again*/ if($arrMatches[3][$i] != ''){ $strEndLst = '</ol>'; if($arrMatches[3][$i] > 1){ $strLstItems = '<ol start="'.$strLstItems[3][$i].'">'; }else{ $strLstItems = '<ol>'; } }else{ $strEndLst = '</ul>'; $strLstItems = '<ul>'; } /* We can split the New lines as we done nl2br() as the top, we split on br */ $arrListItems = split("<br />", $arrMatches[5][$i]); for($x = 0; $x < count($arrListItems); $x++){ /* We dont want empty items, where people double enter or something */ if($arrListItems[$x] != ''){ $strLstItems .= '<li>'.$arrListItems[$x].'</li>'; } } /* Close the item as set above and replace it in our main str */ $strLstItems .= $strEndLst; $str = str_replace($arrMatches[0][$i], $strLstItems, $str); } /* End Handle Lists */ return $str; } Hi guys, I need to find a way to do the following in this string: Code: [Select] {"id":"51","value":["Lorem Ipsum","Lorem Ipsum","new"]} I need to match Code: [Select] "id":"51" If that is matched, I want to remove that ENTIRE string. How would I go about doing that? In other words, I run a preg_match or something like that and if "id":"51" is found, i need to remove the entire element in which it is contained. In this case the element is the above mentioned string. Any ideas? Perhaps with RegEx? (I have no clue how to use RegEx) Hi I have an array from an sql query and i would like to eliminates all the duplicates, i have google search for an answer without success, any help would be aprecciated $result = $stmt->fetchAll(PDO::FETCH_ASSOC); $final = array(); $json = array(); if ($idCoord > 0 || $isDirecao > 0) { foreach ($result as $row) { $idAtividade = $row['idAtividade']; if (!isset($final[$idAtividade])) { $final[$idAtividade]['Escola'] = $row['Escola']; $final[$idAtividade]['Atividade'] = $row['Atividade']; $final[$idAtividade]['Periodo'] = $row['Periodo']; $final[$idAtividade]['Mes'] = $row['Mes']; $final[$idAtividade]['haveClasses'] = $row['haveClasses']; $final[$idAtividade]['DataPrevista'] = $row['DataPrevista']; $final[$idAtividade]['Destinatarios'] = $row['Destinatarios']; $final[$idAtividade]['Orcamento'] = $row['Orcamento']; $final[$idAtividade]['Organizador'] = $row['Organizador']; $final[$idAtividade]['Obs'] = $row['Obs']; $final[$idAtividade]['PdfAtividade'] = $row['PdfAtividade']; $final[$idAtividade]['Avaliacao'] = $row['Avaliacao']; $final[$idAtividade]['idProfessor'] = $row['idProfessor']; $final[$idAtividade]['PdfAvaliacao'] = $row['PdfAvaliacao']; $final[$idAtividade]['Validado'] = $row['Validado']; $final[$idAtividade]['Nome'] = array(); $final[$idAtividade]['Grupo'] = array(); $final[$idAtividade]['Departamento'] = array(); } $final[$idAtividade]['Nome'][] = $row['Nome']; $final[$idAtividade]['Grupo'][] = $row['Grupo']; $final[$idAtividade]['Departamento'][] = $row['Departamento']; } foreach ($final as $idVisita => $reservation) { $json[] = $reservation; } } echo json_encode($json); } And this is an example i'm receiving
So you can see that Grupo has 4 times the value "500" and Departamento has 4 times that string... How can avoid this and have only one value of each?
Thanks
Hi, I have got some data out of my database, I would now like to sort all of this by putting the data into arrays, something looking like this: branch - costs - profit France - 406.85 - 1392.48 So each branch is one item in the array, but has the costs and profit with it too. I would then like to sort those arrays by things like branch name, costs and profit. Is this possible? Hi, currently I have a function searchFolder that simply takes in ONE directory which holds all the xml files I wish to store to db via function writeXMLtoDBviaDOM. I want to make it more robust(realistic) to be able to also search complex directories (so the main directory I pass as parameter to searchFolders) in turn holds sub-directory (which in turn holds further sub-directory) which finally holds all the xml files. here is code: Code: [Select] <?php $dir = "C:/dir/dir2/dir3/"; function searchFolders($dir) { $_filePath=""; $filePathsArray=array();//stores each file $xmlFiles = glob($dir . '*.xml'); if(is_dir($dir)) { // list files $xmlFiles = glob($dir . '*.xml'); //print each file name foreach($xmlFiles as $xmlFile) { print $xmlFile."<br />"; $filePathsArray[]=$xmlFile; } }//END BIG IF retreiving all files in dir param foreach($filePathsArray AS $curFile) { //set up db connection mysql_connect("localhost","root"); mysql_select_db("someDb"); $_filePath=$curFile; $dom=new DOMDocument(); $node=basename($_filePath);//$node is the file name only $dom->load($node); writeXMLtoDBViaDOM($dom->documentElement,$_filePath); }//END FOR-EACH LOOP for each XML file }//END FCN searchFolders VERSION 0 searchFolders($dir);//VERSION 0 ONLY searched 1 simple dir ?> Any help much appreciated! I've been stuck on this for about a week so I was wondering if I can get some help from you guys! Basically I'm exporting an array of values to a CSV file, within that array are two other arrays containing data I need. What I need to work out is how I can create a CSV with headers for these values, then with the nested arrays also print their values into the same rows as the first array. Example: $List = array ( 'Product ID' => '10', 'Customer Address' => '123 Fake Street', array( array('Product Name'=>'Product1', 'Product Price'=>'10.00', 'Product Reference'=>'HGJEN'), array('Product Name'=>'Product2', 'Product Price'=>'5.00', 'Product Reference'=>'HGJTN'), array('Product Name'=>'Product3', 'Product Price'=>'10.00', 'Product Reference'=>'HGJNN'), ), array( array('Product Customisation Name'=>'Additional Info', 'Customisation Value'=>'Things are great.'), array('Product Customisation Name'=>'Image Upload', 'Customisation Value'=>'Logo.jpg'), ), 'Telephone Number'=>'999', ); To be exported to something looking like this: Product ID Customer Address Product Name Product Price Product Reference Product Cus Name Cus Value Telephone Number 10 123 Fake Street Product2 5.00 HGJTN Additional Info Things are great 999 10 123 Fake Street Product1 10.00 HGJEN Image Upload Logo.jpg 999 10 123 Fake Street Product3 10.00 HGJNN 999 If anyone could help me out in anyway I would be so appreciative, I'm sure this ones going to end up killing me! Hi,
Well, I'm having this
The formatter threw an exception while trying to deserialize the message: Error in deserializing body of request message for operation 'GetSomething'. End element 'Body' from namespace 'http://schemas.xmlso.../soap/envelope/' expected. Found element 'param1' from namespace ''.
The soapclient request itself is something with multiple namespaces, like :
<aaa xmlns="namespace1"> <bbb xmlns="namespace2" xmlns:i="http://www.w3.org/20...hema-instance"> <requestparams>xxxxx</requestparams> </bbb> </aaa> So far I think this may got to do with multiple namespaces, so I've been trying to figure out how to deal with this for hours to no avail. Anyone can shed a light into this problem ? Thanks in advance, |