PHP - Complex String Replacement
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) Similar TutorialsHello all, I have a script uploading files on the server. I would like to send a confirmation to user if the file had been uploaded well. Code: [Select] $targetFile = str_replace('//','/',$targetPath) . $filename; move_uploaded_file($tempFile,$targetFile); if (str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile)) { mail($to, 'upload notification', "Dear Mr/Mrs $fixedname, the file entitled $filename has been successfully uploaded"); }else { mail($to, ' upload notification', "Dear Mr/Mrs $fixedname, the file entitled $filename has been NOT uploaded"); } I presume I do something wrong because it doesn't work. The successfull email is sent each time. Thank you very much for helping, Eric I want to duplicate my website but I don't want to have to edit my original files to change like the phone number on the page and upload it to my duplicate site, I just want to either insert coding on my duplicate website that would cause my original website to show up differently, like changing the phone number listed on the page. I am having trouble trying to fix my eregi call in my script. I have a reporting tool that grabs information from the user agent when they email help questions. I used eregi to find the string in an array and print out when it finds a match. I don't fully understand the PCRE functions so i don' t know if i am using them right. what i have is foreach($OSList as $CurrOS=>$Match) { // Find a match if (eregi($Match, $_SERVER['HTTP_USER_AGENT'])) { // We found the correct match break; } } I know i need to change this around for PCRE preg_match maybe but i am not sure. if anyone could send me a tutorial or help me out it would be great. EDIT: notice the foreach was not correct $out = wordwrap($data,400,"@"); $output = explode("@",$out, -1); By default a -1 no longer works properly for me so I need a similar method to get the same output. I made a game back then that reads the php file. So I could change the extension to .php4/.php5 (forget which one would work) the sockets will still link to the default .php file. So how can I fix this? My code for replacing user input is as follows: function Replace_BB($text) { $bb = array( '@\[u\](.*?)\[\/u\]@is', '@\[i\](.*?)\[\/i\]@is', '@\[b\](.*?)\[\/b\]@is', '@\[img\](.*?)\[/img\]@is', '@\[url\](.*?)\[/url\]@is', '@\[url=http://(.*?)\](.*?)\[/url\]@is' ); $html = array( '<u>$1</u>', '<em>$1</em>', '<strong>$1</strong>', '<img src="$1" />', '<a href="$1">$1</a>', '<a href="$1">$2</a>' ); return preg_replace($bb, $html, $text); } print_r (Replace_BB($_POST['data'])); How can I use an if statement to decide how to put in my replacement. So for example: Code: [Select] $html = array( 'IF XXXXXX THEN DO THIS>>>>> <u>$1</u> ELSE DO THIS >>>> <u>$1 Error</u>', Hi, I currently have some PHP scripts that verify form data using ereg() as follows: if (ereg(".",$var1)==0) { //do something } where instead of the argument "." I also use "\@" or "\....*", etc. to test whether certain form input is in the correct format (e.g. testing for a valid email address, etc.). However, I have understood that ereg() is being deprecated. What is the best/easiest function to replace ereg() with? 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 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. 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? 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 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, 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! 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, 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 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 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. 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 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=306845.0 |