Jump to content

Search the Community

Showing results for tags 'array'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Hello there, I'm really new at PHP and I've been reading several beginner tutorials so please accept my apologies for any stupid questions I may ask along the way. I've gotten as far as installing XAMPP, set up a database plus PHP form and I'm struggling to figure out how to insert values from an array into my database. I've learnt the code in one particular way (see beginner tutorials) so I was wondering if you could help me keeping this in mind. I know there'll be a million better ways to do what I'm doing but I fear I will be bamboozled with different code or differently structured code. Anyway the tutuorials I'm reading don't see to cover how I can insert an array of values into my database, just singular values. In the attached file, I have 10 rows of 2x text inputs (20 text inputs total). Each row allows the user to enter a CarID and CarTitle. I've commented out the jQuery which validates the inputs so I can build a rudimentary version of this validation with PHP. I thought that because the line $sql="INSERT INTO carids_cartitles (CarID, CarTitle) VALUES ($id, $title)"; is inside the foreach, means that for each pair of values from the form it'd insert to the database. It doesn't do this. If I enter two or more CarIDs and CarTitles, only one pair of values gets saved to the database. I'm sorry if I haven't explained this well enough, any questions please let me know. Many thanks for your help in advance. form.php
  2. Hi all, I have a looping error in my PHP. I am trying to add use a while statement to gather the users first and last name in to a string, add them to an array called $friendname, then check that the $friendname[] is only output/echoed once. At the moment the code looks good to me but with multiple rows with the same name associated, the name is echoed the same amount of times as rows, instead of once as it is supposed to be. Any ideas anyone? while($row2 = mysqli_fetch_assoc($result2)) { $friendcode = $row2['Code']; $names = "SELECT FirstName, LastName from users WHERE Code = '$friendcode' AND Code != '$crewcode'"; $resultnames = mysqli_query($cxn,$names) or die ("Can't get friends names."); while($rownames = mysqli_fetch_assoc($resultnames)) { $friendname = array(); $newfriendname = ($rownames['FirstName'].' '.$rownames['LastName']); if (!in_array($newfriendname, $friendname)) { array_push($friendname, "$newfriendname"); echo $newfriendname; } } }
  3. hi guys so i have this add contacts page and the form is divided into 3 different froms 1) primary contact 2)spouse 3)child and the child form data is inserted as array into database because in the primary contact part of the form there is a "Children ?" with yes and no radio button and if yes a drop down list is enabled where if user chooses say 2 then there would be 2 child form that appears. and since theres 2 children then in the database a new row and data will be added accordingly. image attached to be clearer. i got it inserted into database but in the specified field it says array: |child_name|dob|house_add1|mobile|office|email| inserted: |array|array-array-array|array|array|array|array| query: "INSERT INTO child VALUES('','".$childsalutations." $childfname $childlname',' ".$cday."-".$cmonth."-$cyear ','$childline1','$childline2','$childm','$childoff','$childemail')" in a stackoverflow question(not my own question) someone says: information stating arrays need to be split, before inserting into the table. does that mean something like this?: $cday = ($_POST['cday']); $cmonth = ($_POST['cmonth']); $cyear = ($_POST['cyear']); $childsalutations = ($_POST['child-salutations']); $childfname = ($_POST['child-fname']); $childlname = ($_POST['child-lname']); $childline1 = ($_POST['child-line1']); $childemail = ($_POST['child-email']); $childm = ($_POST['child-mobile']); $childoff = ($_POST['child-office']); $info = array('c_name' => $childsalutation $childfname $childlname, 'c_dob' => $cday-$cmonth-$cyear, 'c_line1' => $childline1, 'c_mobile' => $childm, 'c_office' => $childoff, 'c_email' => $childemail) just in case u wanted to c the html child form(warning its abit long,very!): <table class="prime"> <tbody> <br> <tr><td style="font-size:20px;font-weight:bold">Child <span id="number"></span></td></tr> <tr> <td>Salutation :</td> <td><select name="child-salutations[]" id="child-salutations"> <option value="" disabled selected>Salutations</option> <option value="Datin">Datin</option> <option value="Datin Paduka">Datin Paduka</option> <option value="Dato Paduka">Dato Paduka</option> <option value="Dato'">Dato'</option> <option value="Dato' Seri">Dato' Seri</option> <option value="Datuk">Datuk</option> <option value="Datuk Seri">Datuk Seri</option> <option value="Dr.">Dr.</option> <option value="Haji">Haji</option> <option value="Hajjah">Hajjah</option> <option value="HM">HM</option> <option value="HRH">HRH</option> <option value="Miss">Miss</option> <option value="Mrs.">Mrs.</option> <option value="Mr.">Mr.</option> <option value="Pehin">Pehin</option> <option value="Professor">Professor</option> <option value="Raja">Raja</option> <option value="Tan Sri">Tan Sri</option> <option value="Tengku">Tengku</option> <option value="Tuanku">Tuanku</option> <option value="Tun">Tun</option> <option value="Tunku">Tunku</option> <option value="Ungku">Ungku</option> </select> </td> </tr> <tr><td colspan="2"><label class="label" style="color:Red">*If a person has many salutations, choose the highest form of salutation</label></td></tr> <tr><td>First Name :</td><td><input type="text" name="child-fname[]" id="child-fname" class="style" /></td> <td>Last Name :</td><td><input type="text" name="child-lname[]" id="child-lname" class="style" /></td></tr> <tr> <td>Date of Birth : </td> <td> <select name="cday[]"> <option value=""selected disabled>Day</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="cmonth[]"> <option value="" selected disabled>Month</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> Year : <input type="text" name="cyear[]" maxlength="4" size="4" class="year"> </td> </tr> <tr><td>Where do they live ?</td><td colspan="3"><input type="radio" name="living[]" id="living-me" class="living-me"/>With Me<input type="radio" name="living[]" id="living-other" class="living-other"/>With Other Parent<input type="radio" name="living[]" id="living-own" class="living-own"/>Own</td></tr> <tr><td>House Address</td></tr> <tr><td>Line 1 :</td><td><input type="text" name="child-line1[]" id="child-line1" size="20" class="style" /></td> <td>Mobile No :</td><td><input type="text" name="child-mobile[]" id="child-mobile" class="style" /></td></tr> <tr><td>Office No :</td><td><input type="text" name="child-office[]" id="child-office" class="style" /></td> <td>Email Address : </td><td><input type="email" name="child-email[]" id="email" class="style" /></td></tr> </tbody> </table>
  4. Hello, i need some help/info about searching words in files (txt or xml) and saving them to db or another file. For example ive got an xml file like below: <families> <family> <name>brown</name> <city>denver</city> <members>12</members> </family> <family> <name>jackson</name> <city>new york</city> <members>6</members> </family> </families> i want to search for: <family> then save the lines till it comes to the word </family> and then goes to the next group. did some reading about array, preg_match, strpos functions but dont know where to start. what is the best way to do this? can you guys give me some advise... or links to good tutorials? thanks in advance!
  5. optionsT Does not show any results.Dont know where is the problem. <script type="text/javascript" language="javascript"> function AddItemInList(fromLeftToRight, isAll){ var list1 = document.getElementById('listBoxF'); var list2 = document.getElementById('listBoxT'); if(Boolean(fromLeftToRight) == true){ MoveItems(list1,list2,isAll); }else{ MoveItems(list2,list1,isAll); } return false; } function MoveItems(listFrom, listTo, isAll){ var toBeRemoved = ""; if(listFrom.options.length > 0){ for (i=0; i<listFrom.length; i++){ if (listFrom.options[i].selected || (isAll == true)){ if(Exist(listTo, listFrom.options[i].value) == 0){ listTo[listTo.length] = new Option(listFrom.options[i].text, listFrom.options[i].value, true); toBeRemoved = toBeRemoved + listFrom.options[i].value + ';'; } } } ClearSelection(listTo); RemoveFromList(listFrom, toBeRemoved); }else{ alert('Unable to Move Items. List is Empty!'); } } function RemoveFromList(listFrom, items){ var toBeRemoved = items.split(';'); for (var i=0; i < toBeRemoved.length; i++){ for (var j = 0; j < listFrom.length; j++){ if (listFrom.options[j] != null && listFrom.options[j].value == toBeRemoved[i]){ listFrom.options[j] = null; } } } } function ClearSelection(list){ list.selectedIndex = -1; } function Exist(list, value){ var flag = 0; for (var i=0; i < list.length; i++){ if (list.options[i].value == value){ flag = 1; break; } } return flag; } </script> <?php $opt = isset($_POST['optionsT']) ? $_POST['optionsT'] : ''; if(!empty($_POST['submit'])){ print $opt; } print" <form method=\"POST\"> <table style=\"width:100%\"> <tr valign=\"top\"> <td>Options</td> <td> <select multiple size=\"5\" name=\"optionsF\" id=\"listBoxF\" style=\"width:350px\"> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> </select> <div align=\"center\"> <input type=\"button\" onclick=\"return AddItemInList(true,true)\" value=\"+ All\"> <input type=\"button\" onclick=\"return AddItemInList(true,false)\" value=\"+\"> <input type=\"button\" onclick=\"return AddItemInList(false,false)\" value=\"-\"> <input type=\"button\" onclick=\"return AddItemInList(false,true)\" value=\"- All\"> </div> <select multiple size=\"5\" name=\"optionsT[]\" id=\"listBoxT\" style=\"width:350px\"> </select> </td> </tr> <tr> <td></td> <td><input type=\"submit\" name=\"submit\" value=\"Submit\"></td> </tr> </table> </form>"; ?>
  6. Hi, This is the output from a var_dump($array); command: array (size=381) 0 => array (size=2) 'Name' => string 'apple' (length=6) 'Number' => float 0.368844763 1 => array (size=2) 'Name' => string 'Blueberry' (length= 'Number' => float 5.59E-6 2 => array (size=2) 'Name' => string 'Cinnamon' (length=5) 'Number' => float -0.0006947 3 => array (size=2) 'Name' => string 'Date' (length=10) 'Number' => float 0.001584453 ... ... ... I want to sort this array from the highest 'Number' float value to the smallest. I tried sorting it with rsort($array,SORT_NUMERIC); but that doesn't give the correct output. What kind of 'sort' should i use to do this?
  7. So I need some help. I know how to create arrays and parse them in PHP (former C/C++/VB programmer, so PHP is easy to figure out), but here's my problem. I have an application where I need to have a 2D array with 2 columns, but indexing doesn't matter, and one or both of the columns could be duplicated, as follows: Price Quantity 200 2 300 1 100 10 200 55 60 1 As you can see, the numbers could be repeated. Ideally, I'd like to do this as an associative array rather than having to add another column as an index column, since the numbers will not need to be referenced, but more or less just added together and summed up. Any ideas on this?
  8. Hi, So I have an array var playlist = new Array(); And in it I have songs as so: playlist[0] = 'Avicii - Levels'; playlist[1] = 'Song'; playlist[2] = 'Song'; playlist[3] = 'Song'; playlist[4] = 'Song'; playlist[5] = 'Song'; playlist[6] = 'Song'; playlist[7] = 'Song'; playlist[8] = 'Song'; playlist[9] = 'Song'; playlist[10] = 'Song'; Now I'm not an expert at MySQL so I was wondering if there would be an easier way to do this with MySQL instead if adding playlist[number] = 'Song"; after every line. It would search the MySQL database for a column named songs and it would automatically put them into the array 'playlist'. Also code examples or a finished product would be VERY helpful! Thanks
  9. I have the following code which prints results from a sqlsrv_fetch_array() using a while loop. For one segment, however, I only need the first $value of the $key=>$value pair, and obviously with the code written this way it returns all rows. I have an idea of an approach, and I'm wondering if I'm headed in the right direction or if anyone has experience with this that they can share. So, during the while loop, I am pushing the elements of the sqlsrv_fetch_array() into a separate array. So I see two potential options: 1. Print from the $actcontacts[] array rather than from the sqlsrv fetch array. 2. During the while loop, rather than pushing anything into a new array, build a conditional that says to only print the record if $row['ENDTIME'] is in position $row[0]. I'm leaning toward #2, but I'm not quite sure how to get there...and if there is a better way under door #3, I would like to try that. while ($row = sqlsrv_fetch_array( $stmt_act, SQLSRV_FETCH_ASSOC) ) { $actcontacts[] = "N/A" . "," . $row['COMPANYNAME'] . "," . $row['CITY'] . "," . $row['STATE'] . "," . $row['CUST_Salesman_124705300'] . "," . $row['ENDTIME'] . "," . "ACT"; // I have done a print_r() on $actcontacts and the data is correct. $endtime[] = $row['ENDTIME']; echo "<tr>"; echo "<td>" . "<i>N/A</i>" . "</td>"; echo "<td>" . $row['COMPANYNAME'] . "</td>"; echo "<td>" . $row['CITY'] . "</td>"; echo "<td>" . $row['STATE'] . "</td>"; echo "<td>" . $row['CUST_Salesman_124705300'] . "</td>"; echo "<td>" . $row['ENDTIME'] . "</td>"; // This is the bugger that is printing eleventy records. It may be one customer, but there are always multiple contact/history entries. echo "<td>" . "ACT" . "</td>"; echo "</tr>"; }
  10. Hi all, I hope you can help me further with this problem. I want to build a quiz/votematch website like this one: http://bit.ly/1kGUGJ6 I want to ask about 20 questions and record all clicked items, so I can use it to match it after the last question. All questions are like this: <div class="stelling" id="stelling4618"> <p>Question 1</p> <h2>The question here.</h2> <a address="true" href="#/stelling/2" class="big botshadow button agree">Eens</a> <a address="true" href="#/stelling/2" class="big botshadow button neutral">Geen van beide</a> <a address="true" href="#/stelling/2" class="big botshadow button disagree">Oneens</a> <a address="true" href="#/stelling/2" class="medium button skip">Sla deze vraag over</a> </div> So if a user click on the first link, <a>eens</a>, I want to push this text to an array with php. After question 20 I want to show all clicked items and match it with my database values. How can I do this? Please help me, I really need this... Thanks so much!! Kind regards, Mark
  11. Hi, I have a csv-file with data like this: I have a mysql database with all the names of the ingredients and a webpage with a searchbox so for example if i search for apple select it and then i search and select blueberry i want to get the corresponding data for apple and blueberry ( -4 in the example ). I know i can read the csv-file with 'fgetcsv' but i'm not sure how to import it into an array so it's easy to use so i can search for ingredients. Does anybody have an idea how to do this in php?
  12. HI, I am a beginner at programing and I have to do this project where it is asking me to validate any ISBN 13 number. I know how to set up the input page, but I am having or you could say no Idea how to validate a number if user inputs data in the input page. I have some could below that I think it should be included, but if someone has better way to do it then I would be appreciate it. here is the input page code: <form method="POST" action="Process_isbn13.php"> <p>Enter the ISBN 13: <input type="text" name="isbn13"/></p> <input type="submit" name="Submit" value="Submit" /> </form> I have this so far for my processing page to validate the ISBN 13 number! <?php function isValidISBN13($isbn) { $sum = 0; for ($i = 0; $i < 13; $i++) { if ($isbn[$i] === 'X') { $value = 13; } else { $value = $isbn[$i]; } $sum += ($i + 1) * $value; } } ?> I know there should be more like if it is empty it should say it's empty do it again and if it is not validate then it would say that. The most important thing I need is the code so if i enter a validate ISBN 13 number it would say it's validate! Someone please help me with the code needed to check if ISBN 13 number is validate.
  13. Hey guys, Sorry, php noob here, but can grasp new concepts rather quickly. I've been in IT a long time and this is my first time trying to rewrite this much php code. I've been working on this php script for 7 days now and think I'm getting close. I've seen most every syntax error, have learned a lot and morphed the code into what it is now. The script I'm hacking was written back in 09 with 16 (static) user data fields in an array to test register a user at a third-party website via SSL with curl and a simple xml load string. If you get a success response, all went well with the other server. If not, all you get is a fail response. The first 6 data fields will still remain static, but the last 10 will always vary because I'm querying a WP user DB to get user data. The script just queries the WP user DB creates an array and posts to the other server and registers the user, so the user that registered with the first site doesn't have to go through the whole registration process over again. This is totally G-rated. It's for a consumer discounts site. Here's what I'm trying to get the code to do. Create an array, query the DB and then pass the first static array data and the user array data to the post string and get a success response from the other server. This is the whole script that's failing and I'm only able to see, Status: fail. Nice error code huh? Here's my code: error_reporting(E_ALL); ini_set('display_errors',true); // Set the Query POST parameters $query_vals = array( 'api_username' => 'api-name-here', 'api_password' => 'api-password', 'api_key' => 'key-goes-here', 'perkalert' => 0, 'offer_radius' => 20, 'send_welcome_email' => 1 ); // Call WordPress function wp_get_current_user_info() //Create array function wp_get_current_user_info() { $current_user = wp_get_current_user(); $current_user-> $value; $n="user_variable_{$type}_name"; ${$n} = true; $current_user_info = array( 'firstname' . $current_user->user_firstname =>'n', 'lastname' . $current_user->user_lastname =>'n', 'address' . $current_user->mepr-address-one =>'n', 'city' . $current_user->mepr-address-city =>'n', 'state' . $current_user->mepr-address-state =>'n', 'zip' . $current_user->mepr-address-zip =>'n', 'country' . $current_user->mepr-address-country =>'n', 'email' . $current_user->user_email =>'n', 'username' . $current_user->user_login =>'n', 'password' . $current_user->user_pass =>'n' ); return $current_user_info; } $postdata = ''; $key = '='; $value = '&' $query_vals = array(); $current_user_info = array(); $result = array_merge($query_vals, $current_user_info); { foreach($query_vals as $key => $value); foreach($current_user_info as $key => $value); $postdata .= $key.'='.urlencode($value).'&'; } // Chop of the trailing ampersand $postdata = rtrim($postdata, '&'); // create a new cURL resource $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://secureserver/client/register_member.xml'); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); // Save response to a string $response = curl_exec($ch); curl_close($ch); $xml = simplexml_load_string($response); //var_dump($xml); echo "Status: ".$xml->status; Any help is really appreciated. Thanks.
  14. Hi guys, I was wondering, is it possible to split an array into pages with 10 values on each page? And how can I make a navigation bar with Page 1 2 3 in it? And if it's possible, how would I do that? Thanks in advance, iRoot121
  15. I have two arrays and all I want from them is the differences to show and any item that existed in both not to show. Please find my workings below mysql_select_db($database_dbconnect, $dbconnect);$query_Asset = "SELECT idAsset, AssetName FROM Asset WHERE idLocation = '1'";$AssetUp = mysql_query($query_Asset, $dbconnect) or die(mysql_error()); $array1 = array(); while ($f = mysql_fetch_assoc($AssetUp)) {$array1[] = $f;} mysql_select_db($database_dbconnect, $dbconnect);$query_DocUp = "SELECT Asset.idAsset, Asset.AssetName FROM AssetDocStand INNER JOIN Asset ON AssetDocStand.idAsset = Asset.idAssetWHERE AssetDocStand.idDocumentStandards = '2' AND Asset.idLocation ='1'";$DocUp = mysql_query($query_DocUp, $dbconnect) or die(mysql_error());$array2 = array(); while ($f = mysql_fetch_assoc($DocUp)) {$array2[] = $f;} print_r($array1); echo "<br><br><br>"; print_r($array2); shows the following when the page is loaded. Array ( [0] => Array ( [idAsset] => 10000005 [AssetName] => HP ) [1] => Array ( [idAsset] => 10000006 [AssetName] => HP Server ) [2] => Array ( [idAsset] => 10000009 [AssetName] => HP Laptop ) [3] => Array ( [idAsset] => 10000010 [AssetName] => Office Printer ) [4] => Array ( [idAsset] => 10000023 [AssetName] => test ) ) Array ( [0] => Array ( [idAsset] => 10000023 [AssetName] => test ) ) Now when i type $array3 = array_diff($array1, $array2 ); print_r($array3); I get Array ( ) Ive also tried array_diff_key() which also produces nothing. All I want to be left with is Array ( [0] => Array ( [idAsset] => 10000005 [AssetName] => HP ) [1] => Array ( [idAsset] => 10000006 [AssetName] => HP Server ) [2] => Array ( [idAsset] => 10000009 [AssetName] => HP Laptop ) [3] => Array ( [idAsset] => 10000010 [AssetName] => Office Printer ))
  16. Hi guys, Users of my website will be copying and pasting their work schedule from another website that displays it in a html table, as shown below, in to a textarea on my website which I can then decode and store in a mysql db. To do this I am trying to put every value in to an array with the associated column name/key. |Date| |Duty| |Dep| |Start| |End| |Arr| 4 Apr 14, Fri 3005 (Z) CIA 04:15 Z 07:05 Z STN 4 Apr 14, Fri 3002 STN 07:45 Z 10:15 Z CIA 5 Apr 14, Sat OFF (Z) CIA 00:00 Z 21:00 Z The small problem being both the 'Duty' and 'Arr' column can have any numerical, text or blank spaces in them. All the other columns have the same format in every row. (such as the 'Dep' column is always 3 uppercase characters etc). I have tried to separate the parts of each line as you can see in the code below but this would not be consistent due to the extra spaces the sometimes occur in the 'Duty' column. Does anyone see a way to make this fault proof?! Thanks <?php $lines = explode("\n", $_POST['test']); $sector = 1; foreach($lines as $line) { if(substr($line, 0, 4)=='Date') { //Skip header line continue; } $parts = preg_split('/\s+/', $line); echo 'Sector '.$sector.'<br />'; $date = $parts[0] . '/' . $parts[1] . '/20' . trim($parts[2], ','); $duty = $parts[4]; $dep = $parts[5]; $begin = $parts[6]; $end = $parts[8]; $arr = $parts[10]; $sector++; } ?>
  17. i have a problem with a script, the script read a file (csv) and stores the last value of each line in an array, then i calculate the maximun,minimun and average of the values in the array, but with big files the script give me an incorrect value for the maximun,minimun and average, with the file 8.csv the calculations are correct but with the file 1.csv the values are wrong, the only difference i see is that the file 1.csv is much larger than the other. Thanks for your help!!! This is the code: <?php $variable2=file("1.csv"); $i=0; foreach($variable2 as $var){ if($i==0){ $i++; }else{ $datos=explode(",",$var); $valor=$datos[count($datos)-1]; if($valor!= -3000){ $todos[$i-1]=$valor; $i++; } } } $promedio=array_sum($todos) / count($todos); $maximo=max($todos); $minimo=min($todos); echo "MAXIMO = ".$maximo." MINIMO = ".$minimo." PROMEDIO = ".$promedio; ?> And this is a part of the file 1.csv (the full file have more than 60.000 lines) OBJECTID,pointid,grid_code,potrero_ID,MOD13Q1.A2 7300.0,7300.0,1.0,1,6431 7498.0,7498.0,1.0,1,6684 7499.0,7499.0,1.0,1,6431 7500.0,7500.0,1.0,1,6431 7501.0,7501.0,1.0,1,6431 7502.0,7502.0,1.0,1,6431 7503.0,7503.0,1.0,1,6431 7504.0,7504.0,1.0,1,6304 7697.0,7697.0,1.0,1,6734 7698.0,7698.0,1.0,1,6734 7699.0,7699.0,1.0,1,6127 7700.0,7700.0,1.0,1,6127 Expected values: Maximun: 9307 Minimun: -650 Average: 6555,211347 Output values: Maximun: 999 Minimun: -104 Average: 6555,3296310272 If you want you can download the code and input files here: https://www.dropbox.com/s/y4vpjm6086rj3s3/script.zip Thanks.
  18. Hello guys. I execute a query and then put the records into array, the query has ORDER BY .... why I don't have the same order in the array?, If I execute the query, the record one it's no the same that $arreglo[0]. $stmt = $this->db->prepare('SELECT a.id_torneo, b.tor_nombre, a.id_jornada, a.id_juego, a.cal_fecha_hora, id_arbitro, a.cal_estatus, a.cal_default, c.id_equipo, d.equ_nombre, c.enc_locvis, e.id_jugador, e.jug_nombre_pila, e.jug_apellido_pat, e.jug_apellido_mat, e.jug_representante, e.jug_numero, jug_fechimp_reg FROM calendario a, torneo b, encuentro c, equipo d, jugador e WHERE a.id_cliente =? AND a.id_sucursal = ? AND date(a. cal_fecha_hora)= date(?) AND a.id_cliente = b.id_cliente AND a.id_sucursal = b.id_sucursal AND a.id_torneo = b.id_torneo AND a.id_cliente = c.id_cliente AND a.id_sucursal = c.id_sucursal AND a.id_torneo = c.id_torneo AND a.id_jornada = c.id_jornada AND a.id_juego = c.id_juego AND a.id_cliente = d.id_cliente AND c.id_sucursal = d.id_sucursal AND c.id_torneo = d.id_torneo AND c.id_equipo = d.id_equipo AND d.id_cliente = e.id_cliente AND d.id_sucursal = e.id_sucursal AND d.id_torneo = e.id_torneo AND d.id_equipo = e.id_equipo AND e.jug_estatus = "A" ORDER BY 5,11') or die(mysqli_error($this->db)); $stmt->bind_param("iis", $cliente, $sucursal, $fecha); $stmt->execute(); $stmt->bind_result($id_torneo, $tor_nombre, $id_jornada, $id_juego, $fecha_partido, $id_arbitro, $cal_estatus, $cal_default, $id_equipo, $equipo_nombre, $locvis, $id_jugador, $jug_nombre, $jug_apellidop, $jug_apellidom, $jug_rep, $jug_playera, $jug_fechareg); $arreglo = array() ; $contador = 0; while ($stmt->fetch()) { $arreglo[$contador] = array("id_torneo"=>$id_torneo,"torneo_nombre"=>$tor_nombre,"id_jornada"=>$id_jornada,"id_juego"=>$id_juego,"fecha_partido"=>$fecha_partido,"id_arbitro"=>$id_arbitro,"cal_estatus"=>$cal_estatus,"cal_default"=>$cal_default,"id_equipo"=>$id_equipo,"equipo_nombre"=>$equipo_nombre,"locvis"=>$locvis,"id_jugador"=>$id_jugador,"jug_nombre"=>$jug_nombre,"jug_apellidop"=>$jug_apellidop,"jug_apellidom"=>$jug_apellidom,"jug_rep"=>$jug_rep,"jug_player"=>$jug_playera,"jug_fechareg"=>$jug_fechareg); $contador++; }
  19. Hello I have two arrays, and both I want to convert in one like this structure .... both arrays are Equipos array and Jugadores array, how can I do? Regards Equipos 0 id_equipo : 5 nom_equipo: San Blas locvis: L Jugadores 0 id_jugador : 1 name: Robert
  20. Overview: Sort unique string from an array and display results into a variable which can be echoed into jQuery to be displayed as a graph. I using Wordpress with a repeater from custom post fields plugin, code below: $repeater = get_field('treatments'); foreach( $repeater as $key => $row ) { column_id[ $key ] = $row['treatment_name']; } array_multisort( $column_id, SORT_ASC, $repeater ); foreach( $repeater as $row ) { print_r($row); } The print_r returns.. Array ( [treatment_name] => back pain [pain_level] => 4 ) Array ( [treatment_name] => back pain [pain_level] => 5 ) Array ( [treatment_name] => back pain [pain_level] => 7 ) Array ( [treatment_name] => back pain [pain_level] => 10 ) Array ( [treatment_name] => shoulder pain [pain_level] => 3 ) Array ( [treatment_name] => shoulder pain [pain_level] => 8 ) Array ( [treatment_name] => shoulder pain [pain_level] => 10 ) I wish to be able to sort the array data into a variable I can using within JS. { treatment: '1', a: 4, b: 3 }, { treatment: '2', a: 5, b: 8 }, { treatment: '3', a: 7, b: 10 }, { treatment: '4', b: 10 }, A = back pain B = shoulder pain [treatment_name] - is a text field, so I looking for every unique [treatment_name] to added for example having one treatment called 'foot ache' with the pain level of 6 would be added to the start of the list as C. e.g. { treatment: '1', a: 4, b: 3, c: 6 }, { treatment: '2', a: 5, b: 8 }, { treatment: '3', a: 7, b: 10 }, { treatment: '4', b: 10 }, I have gone over and over trying to work the logic out but seems my level of php is not up to par, so I thought no better place to asked then the people who got me this far.. Any questions please do let me know, and anyone will to help your a star..
  21. Hello guys I Have to try to build an array that has a tree structure(4 levels), but I have gotten an error when I tried to put the 2 level ... commands out of sync; you can't run this command now. I attached a file with the code, what's wrong? Regards. code.txt
  22. Hi PHP Freaks! I'm one of the newer users here, yep. And this is my first post here ^.^ I have recently started working on my very simple script in PHP. Parse username/password, perform checks against array to see if username exists and if password is correct for specified user. Print out a message as a finish result. And here is what my problem is.. So far I have written this code (PHP): <?php // List of users and their password. $users = array(1 => 'admin', 2 => 'UserTwo', 3 => 'UserThree', 4 => 'UserFour'); $pass = array(1 => '1234', 2 => 'second', 3 => 'third', 4 => 'fourth'); // Compare username parameter against users list (check if user exists). if (in_array($_GET['username'], $users)) { // User is found. Compare password parameter against pass list corresponding to user ID in array. $userId = array_search($_GET['username'], $users); // Compare password parameter against pass list (using specific userId to check if password is valid). if ($_GET['password'] != $pass[userId]) { echo 'You have entered invalid password.'; } else { echo 'Welcome, '.$_GET['username'].'!'; } } else { // User is not found. echo 'You have entered invalid user name.'; } ?> I guess some of you experienced in PHP understand what I am doing up there Basically I wanted to parse username/password arguments to the URL. That works just fine ( echo $_GET['username'] . '<br>' . $_GET['password']; ) ( Just a note, I use Xampp, so it is http://localhost/login.php?username=admin&password=1234 ) Problem starts at line 9.. I am unsure about that part (I just written it out of my mind and little documentation I have found on their official website) with userId and then comparing it to correspond to the user (like like associating password to specific user id, users[0] = admin to have password 1234, users[1] , and so). Could somebody fix this and post up the code, much appreciated (excuse me for little English mistakes, it is not my native language, I do my best to keep it well) Also include a little description or just explain it in several words, what/where I messed up Thanks in advance. Regards, - OmegaExtern
  23. I have been trying to finish up a website for a while now and I can't seem to figure out how to do this. Right now I want one out of four pictures to randomly be selected and presented on a webpage. I have already achieved this through the shuffle() function. However, I want the name of whichever picture shows up to be recorded in my MySQL database. How do I go about doing this? I searched online and came across the function serialize(), but then I was advised not to use it since I only wanted the name of one of the pictures in the array instead of all of them. Does anyone have any functions/sample code that may be of use? (Example in case I didn't explain clearly: I have four pictures: a.ipg, b.jpg, cjpg, d.jpg Let's say the shuffle() function choses b.jpg to be displayed on the webpage. How could I get b.jpg to be sent to my database?) Thank you.
  24. Hi there, I've posted this at stackoverflow but did not receive any replies so far so I'd like to try here as well. ------ I have an array of variable dimensions and namings. Sometimes associative, sometimes partially. Sometimes just a single array, sometimes multiple dimensions. An example array is this: array(4) { ["name"]=> string(9) "Some Name" ["user"]=> array(2) { ["id"]=> int(1) ["msgs"]=> array(3) { [0]=> string(16) "My first message" [1]=> string(17) "My second message" ["folder"]=> array(2) { ["first"]=> string(13) "Some folder.." [1]=> string(17) "some other stuf.." } } } [0]=> string(17) "More random stuff" ["foo"]=> array(2) { [0]=> string(10) "more stuff" ["bar"]=> string(7) "The end" } } I would like to have a function that goes through every key and value pair and performs a function, without altering the structure of the array. In this case, I want to apply htmlspecialchars() with ENT_QUOTES on every key and value pair in the array while keeping the array itself intact structure wise. I have tried with array_walk_recursive and array_map, neither seem to do the trick. I'm pretty new to PHP but I tried the following function by messing about with how I think it should be done but it's obviously not working private function CreateErrorArray($array, $knownKeys=NULL) { if (is_array($array)) { foreach ($array as $key => $value) { if (is_array($value)) { if (is_null($knownKeys)) { $keys = array($key); $this->response['ERRORARRAY'][$key] = $this->CreateErrorArray($this->RequestClass->error[$key], $keys); } else { $keys = array_push($knownKeys, $key); $this->response['ERRORARRAY'][$key] = $this->CreateErrorArray($this->RequestClass->error[$knownKeys][$key], $keys); } } else { $this->response['ERRORARRAY'][$key] = $value; } } } }
  25. Hello, i have the following code: php 5, ms server 2008, iis 7 I pass this script a csv list of file paths like so... ,C:\path\path\path\file.name,C:\path\path\anotherFile.name,C:\path\path\path\file3.file (yes there is a leading comma in the string for some reason..) $files = $_POST['files']; $files = explode(',', $files) foreach($files as $filename){ if(file_exists($filename)){ echo '":' . $filename .':"Does Exist<br />'; } else { echo 'Sorry ":' . $filename . ':" Does Not Exist<br />'; } } My problem: the first file path shows it exists and there is no white space in the string, all the file paths after the first one show like such: ":C:\path\path\path\file.name:" Does Exist // 1st path (good) ": C:\path\path\anotherFile.name :" Does Not Exist ": C:\path\path\file3.file:" Does Not Exist pleas note... i put the ": and :" in there to show that there is indeed a white space character in front of and behind the filepaths. EXCEPT for the last path.. there is no trailing white space there. Please explain why you think the white space is being added to these and what i can do to get rid of it. thanks, dogdaynoon
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.