PHP - Trim Array (remove Lowest And Highest Values)
(1)
I need to remove the lowest and higest values from an array. I need to actually remove the two lowest and two highest. I suppose the best thing would be to sort the array and then use a function that just drops the first and last values (twice). Is this the best way? Which function would drop the lowest / highest values? (2) I then need to get the remaining first and last (highest and lowest) values. $array[0] would get first, and revesing the order and $array[0] again would get the last. Is this the best way? Similar TutorialsHi folks, i have a complex problem (for me anyway) but i am sure with your help this can be sorted. Problem number 1: I have a simple while loop, but its only showing 4 results when i know there are 5 I am missing something very simple i know: $sql = ("SELECT * FROM postcode WHERE unid='1'")or die ('<p>There seems to be a problem, please try again soon.</p>'); $result = mysql_query($sql,$con); $row = @mysql_fetch_array($result); $i=0; while ($row = @mysql_fetch_assoc($result)){ echo "newpoints[". $i++ ."] = new Array({$row['lat']}, {$row['long']}, icon0, '{$row['postcodename']}', '{$row['postcodename']}'); \n"; } What am i missing here? Problem number 2: I have a bunch of latitude and longitude codes stored in the database. On each page there will be a varied amount of these codes used, but with a max of 20. I need to find the highest number and the lowest number of each lat and long then come up with a code that is in the middle, the idea of this is to center a map. So for example there will be an array like this: 50.852293 -1.76088 51.252938 -0.76128 51.259583 -0.727168 51.274 -0.837 51.123106 -0.970657 First i need to find the highest number of the first code (51.274) then the lowest number (50.852293) and then the highest number of the second code (-1.76088) then the lowest number (-0.727168) Then work out an inbetween code using the highest and lowest codes for each. Does anyone have a clue how to go about this? I am not the worlds best array technition or mathematician I have mysql select query shown below retrieving data from a database:
$sql = " SELECT student, sum( test_score ) as score FROM test INNER JOIN level ON test.level_id = level.level_id GROUP BY student" $result = $mysqli->query($sql, MYSQLI_STORE_RESULT); if($result) { while ($row = $result->fetch_array(MYSQLI_ASSOC)) { var_dump($row); } }On inspection of the retrieved array with var_dump(), i have these result below: array (size=2) 'John' => string 'English' (length=2) 'Score' => string '20' (length=3) array (size=2) 'Mary' => string 'Math' (length=3) 'Score' => string '35' (length=3) array (size=2) 'Samuel' => string 'Physics' (length=3) 'Score' => string '5' (length=3)How do I get at and print out the highest score from this set of array values within this context. I tried this echo max($row['count']) but i understandably got this feedback: Warning: max(): When only one parameter is given, it must be an array Thanks. Hi, I have an array filled with values like this: Code: [Select] string(1) "Acer 1" string(2) "Acer 2" string(3) "Dell 1" string(4) "Dell 2" string(5) "Dell 3" string(6) "Dell 4" string(7) "Acer 3" string(8) "Acer 4" Is there a way to successfully remove all array strings that starts with a given value like "Acer"? I tried with this snippet, does not work: Code: [Select] foreach($array as &$value) { if(preg_match("/^Acer/", $value)) { unset($value); } } Any ideas will be appreciated! Hi all, I'm looking for some pointers in regards to my form.. How would I firstly trim the $_POST value of the variables that come through via the form (I'm only using one for now)..I know I'm making a right dogs dinner of it. In my head I'm thinking, trim all the posts first before i even assign a variable to it ( i dont know if thats possible), then use an array for when more values start coming through via the form. You know as i make a contact form that requires more data from the user..
<?php require_once '../connection/dbconfig.php'; include_once('../connection/connectionz.php'); //get the values //Get the request method from the $_SERVER $requestType = $_SERVER['REQUEST_METHOD']; //this is what type //echo $requestType ; if($requestType == 'POST') { //now trim all $_POSTS $search_products = trim($_POST['search_products']); // if(empty($search_products)){ echo '<h4>You must type a word to search!</h4>'; }else{ $make = '<h4>No match found!</h4>'; $new_search_products = "%" . $search_products . "%"; $sql = "SELECT * FROM product WHERE name LIKE ?"; //prepared statement $stmt = mysqli_stmt_init($conDB); //prepare prepared statements if(!mysqli_stmt_prepare($stmt,$sql)) { echo "SQL Statement failed"; }else{ //bind parameters to the placeholder mysqli_stmt_bind_param($stmt, "s", $new_search_products ); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); echo'<h2> Search Result</h2>'; echo 'You searched for <strong><em>'. $search_products.'</em></strong>'; while($row = mysqli_fetch_assoc($result)){ echo '<h4> (ID : '.$row['pid']; echo ') Book Title : '.$row['name']; echo '</h4>'; } } } } ;?>
If any one can shed some light on this, or some pointers..that would be very nice... Thanks Darren
Hello, I need to set a CSS class for the highest number in a MySQL column, and the second highest. So for instance I have a column named scores. I would want the <td> with highest scores to be <td.Winner> and the second highest to be <td. RunnerUp>. I know how to set the css part up, so just need help with creating a function. I did something similar to set the background of table cells based on the text data and that looked like this. function cssfromdate($date) { $class = array('December_January' => 'January', 'March_April' => 'March'); return $class[$date]; } while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['last_name'] . "</td>\n"; echo "<td>" . ucwords($row['first_name']) . "</td>\n"; echo "<td class=\"".cssfromdate($row['Class_Date'])."\">".$row['Class_Date']."</td>\n"; echo "</tr>"; } I am hoping I can accomplish what I need to doing something similar. Hey Is there a way to trim the print_r($array); so its completed and void of white space? It prints like this: Code: [Select] Array ( [0] => Array ( [id] => 10 [f] => data/tiles/image.png ) ) But I want it to be compressed like this: Code: [Select] Array([0]=>Array([id]=>10[f]=>data/tiles/image.png)) This is then to be stored in the database, so any compressed possible is a plus in this situation. Any ideas? Is there a way to apply the function trim() on a whole array, instead of applying it to the individual input fields one by one? Here's the code: $blurb1_title = array ( $_POST['blurb1_title1'], $_POST['blurb1_title2'], $_POST['blurb1_title3'], $_POST['blurb1_title4'], $_POST['blurb1_title5'] ); $blurb2_title = array ( $_POST['blurb2_title1'], $_POST['blurb2_title2'], $_POST['blurb2_title3'], $_POST['blurb2_title4'], $_POST['blurb2_title5'] ); $blurb3_title = array ( $_POST['blurb3_title1'], $_POST['blurb3_title2'], $_POST['blurb3_title3'], $_POST['blurb3_title4'], $_POST['blurb3_title5'] ); All those $_POST variables are input fields, and I would like to apply trim() to them so the spaces get removed. Is there an efficient way to do it without having to apply it all individually, if yes, what would be the correct syntax? [php] Ok, this was driving me nuts. I think I found the cause, but need help fixing it. I have a bunch of answers in a MySQL database in the form of... Miami Heat/heat/miami Orlando Magic / orlando/ magic etc. etc. *Notice how sometimes there are leading or ending spaces (i.e there is a space before "magic" but NOT a space before "miami")... I run this code to bring back the answers data (all acceptable answers) in an array. I then look for the user entered answer ($userinput, which has trim and strtolower run on it) in the array. Using this code below, the answer IS found if $userinput is any of the Miami Heat options, but it is NOT found if it's any of the Orlando Magic options. The only difference is the fact that there are spaces in the Orlando Magic stuff. Apparently, the trim() function is only removing space from the beggining and end of the ENTIRE string. But I need to trim() each item in the array. How can I do this? Seems like it should be easy but can't figure it out. Code: [Select] $sql = "SELECT * FROM answers WHERE quizid = $quizid"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { while ($getanswers = mysql_fetch_array($result)) { $array = explode("/", strtolower(trim($getanswers['answer']))); if (in_array($userinput,$array)) { echo "the answerid = " . $getanswers['answerid'] . "<br>"; } else { echo "the answerid is not found= <br>"; } } } I have a Form with 10 Questions that a User can choose to answer. I am trying to store the "Answers" into an array like this... Code: [Select] <!-- Question 1 --> <label for="question1">1.) Why did you decide to start your own business?</label> <textarea id="question1" name="answerArray[0]" cols="60" rows="8"><?php if (isset($answerArray[0])){echo htmlentities($answerArray[0], ENT_QUOTES);} ?></textarea> <?php if (!empty($errors['question1'])){ echo '<br /><span class="error">' . $errors['question1'] . '</span>'; } ?> <br /> <!-- Question 2 --> <label for="question2">2.) What advice would you share with others on what NOT to do?</label> <textarea id="question2" name="answerArray[1]" cols="60" rows="8"><?php if (isset($answerArray[1])){echo htmlentities($answerArray[1], ENT_QUOTES);} ?></textarea> <?php if (!empty($errors['question2'])){ echo '<span class="error">' . $errors['question2'] . '</span>'; } ?> <br /> The problem is that when I process the Form, this code is causing issues... Code: [Select] if ($_SERVER['REQUEST_METHOD']=='POST'){ // Form was Submitted (Post). // Initialize Errors Array. $errors = array(); // Trim all form data. $trimmed = array_map('trim', $_POST); I get this error... Code: [Select] Notice: Array to string conversion in /Users/user1/Documents/DEV/++htdocs/05_Debbie/members/create_thoughts.php on line 58 Call Stack # Time Memory Function Location 1 0.0014 93944 {main}( ) ../create_thoughts.php:0 2 0.0716 102640 array_map ( ) ../create_thoughts.php:58 How can I either fix my code or change things to do what I need? Thanks, Debbie I currently have an array that I've built that dumps like this:
0 => array:11 [▼ "category_code" => "123" "category_name" => "Testing" "category_description" => "This is a test category" 19738 => array:5 [▼ "identifier" => "720368842943" "description" => Test Description One "count" => 4 "details" => array:2 [▼ 0 => array:3 [▼ "detail_code" => "2751" "detail_code2" => "43" "detail_specifier" => "Detail One" ] 1 => array:3 [▼ "detail_code" => "2681" "detail_code2" => "9" "detail_specifier" => "Detail Two" ] ] "prices" => array:1 [▼ "01" => "1129.00" ] ] 19739 => array:5 [▼ "identifier" => "720368844121" "description" => "Test Description Two" "count" => 4 "details" => array:2 [▼ 0 => array:3 [▼ "detail_code" => "2751" "detail_code2" => "43" "detail_specifier" => "Detail One" ] 1 => array:3 [▼ "detail_code" => "2681" "detail_code2" => "9" "detail_specifier" => "Detail Two" ] ] "prices" => array:1 [▼ "01" => "1490.00" ] ] I'm using laravel excel in order to export that as an excel file, but it's not quite working the way I intend When it exports to excel I only get the top level info: 123 | Testing | This is a test category But I want to get that info as a header and then each subsequent product for that category as a row, so with the example above it would look like:
123 | Testing | This is a test category Here's the excel code with the array I'm using, which is dumped above: $allCategoryResult= array(); foreach($prices->categories as $category){ $categoryItem = array(); $categoryItem["category_code"] = $category->category_code; $categoryItem["category_name"] = $category->category_name; $categoryItem["category_desc"] = $category->category_desc; foreach($category->skus as $sku){ $skuItem = array(); $skuItem["identifier"] = $sku->sku_info->identifier; $skuItem["description"] = $sku->sku_info->item->description; $skuItem["count"] = $sku->sku_info->item->item_type->count; $skuItem["details"] = array(); foreach ($sku->sku_info->details as $details) { $detailsItem = array(); $detailsItem["detail_code"] = $details->detail_code; $detailsItem["detail_code2"] = $details->detail_code2; $detailsItem["detail_specifier"] = $details->detail_specifier; $skuItem["details"][] = $detailsItem; } $skuItem["prices"] = get_object_vars($sku->prices); $itemCode = $sku->sku_info->item->item_code; $categoryItem[$itemCode] = $skuItem; } $allCategoryResult[] = $categoryItem; } $name = 'Test Export'; $build = Excel::create($name, function ($excel) use ($allCategoryResult) { $excel->setTitle('Test Export'); $excel->sheet('Test Export', function ($sheet) use ($allCategoryResult) { $sheet->fromArray($allCategoryResult);
I have written code in php to connect and insert rows into a MSSQL database. i used odbc to connect database.user can enter his details through the form. after submitting the form the details are getting stored into a database. while inserting rows into a database am not trying to insert duplicate values . for this i have given if conditions.these conditions are able to notice the user cname and name exist in the database if the same name exist. but the else part after these conditions are not working i.e rows are not getting inserted. i put everything inside the while loop. how can i correct it? This is my php code. $connect = odbc_connect('ServerDB','sa', 'pwd'); //connects database $query2="select count(*) from company";//this is needer for loop through $result2=odbc_exec($connect,$query2); while(odbc_fetch_row($result2)); { $count=odbc_result($result2,1); echo "</br>","$count"; } $query1="select * from company"; $result1 = odbc_exec($connect, $query1); # fetch the data from the database while(odbc_fetch_row($result1)) { $compar[$count] = odbc_result($result1, 1); $namearray[$count] = odbc_result($result1, 2); if($compar[$count]==$_POST['cname']) { echo "<script> alert(\"cname Exists\") </script>"; } else if($namearray[$count]==$_POST['name']) { echo "<script> alert(\"Name Exists\") </script>"; } else { $query=("INSERT INTO company(cname,name) VALUES ('$_POST[cname]','$_POST[name]') "); $result = odbc_exec($connect, $query); echo "<script> alert(\"Row Inserted\") </script>"; } } Hi all, I'm a first time poster here and I would really appreciate some guidance with my latest php challenge! I've spent the entire day googling and reading and to be honest I think I'm really over my head and need the assistance of someone experienced to advise the best way to go! I have a multi dimensional array that looks like (see below); the array is created by CodeIgniter's database library (the rows returned from a select query) but I think this is a generic PHP question as opposed to having anything to do with CI because it related to working with arrays. I'm wondering how I might go about searching the array below for the key problem_id and a value equal to a variable which I would provide. Then, when it finds an array with a the matching key and variable, it outputs the other values in that part of the array too. For example, using the sample data below. How would you recommend that I search the array for all the arrays that have the key problem_id and the value 3 and then have it output the value of the key problem_update_date and the value of the key problem_update_text. Then keep searching to find the next occurrence? Thanks in advance, as above, I've been searching really hard for the answer and believe i'm over my head! Output of print_r($updates); CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id] => Resource id #35 [result_array] => Array ( ) [result_object] => Array ( ) [current_row] => 0 [num_rows] => 5 [row_data] => ) Output of print_r($updates->result_array()); Array ( [0] => Array ( [problem_update_id] => 1 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Some details about a paricular issue [problem_update_active] => 1 ) [1] => Array ( [problem_update_id] => 4 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Another update about the problem with an ID of 3 [problem_update_active] => 1 ) [2] => Array ( [problem_update_id] => 5 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of four [problem_update_active] => 1 ) [3] => Array ( [problem_update_id] => 6 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of 6 [problem_update_active] => 1 ) [4] => Array ( [problem_update_id] => 7 [problem_id] => 3 [problem_update_date] => 2010-10-12 [problem_update_text] => Some new update about the problem with the ID of 3 [problem_update_active] => 1 ) ) Hi I am having trouble using the min() function to find the lowest value within my session arrays. On my site i have the following car values saved into my $car array: Code: [Select] $car = array( "itemNumber" => $itemNumber, "Model" => $Model, "EngineSize" => $EngineSize, "Colour" => $Colour, "Value" => $Value, ); I then store each $item array into a $_SESSION['all'] as below: Code: [Select] if (isset($_SESSION['all'])) { $_SESSION['all'][$number] = $car; } else { $_SESSION['all'] = array($number => $car); } Now i need to find the lowest Value of all the cars that the user may add. I have been using the min() function to try and do this with the following code but it gives me the error: Wrong parameter count for min()..... Code: [Select] $cheapest = min($car['Value']); Am i on the right tracks or is this not possible? If anyone could shed some light on how i can get this to work, would be very much appreciated! Hi all, Just a pretty basic question that I can't find the asnwer to: I have a MySQL query of the following form: Code: [Select] $result = mysql_query (" SELECT $cols FROM tablename WHERE......."); Where $cols is as follows: Code: [Select] $cols = firstname, lastname, $price1, $price2, etc. ($price1 and $price2 are variable column names that contains prices) How do I find the lowest value for $price1 and/or $price2 out of the results set of this query? Thanks! Hello all, I have yet again trouble finding a logical solution to my problem. I'm fetching an array which can hold 1 or more values. The problem is, I want these values to ouput in my json_encode function, but this also needs to happen dynamically depending on the amount of values. I can't explain it further, so here's the code so far: Code: (php) [Select] $files = mysql_fetch_array($get_files); $a = count($files); $i = 1; while ($files) { $variablename = 'fileName' . $i; $$variablename = $files['fileName']; $i++; } $output = array( OTHER VALUES , 'fileName1' => $fileName1, 'fileName2' => $fileName2, 'fileName3' => $fileName3, ............); // How do I add the fileNames dynamically depending on how many there are? This got me thinking, I also need to dynamically GET the values with jQuery. How would I do that, when the above eventually works? Thank you. Hi there, Basic question, but I can't seem to find a page in the PHP docs that answers (though I'm sure such a one exists, I just can't seem to think up the right search terms - anyway) My question is: is there a short-hand way to use a value from an associative array as the key in another associative array? So for example, given this array: $the_array = array(0 => array('name': 'the_name', 'value' : 'the_value'), 1 => etc....); then this kind of foreach loop doesn't work Code: [Select] $new_data = array(); foreach($the_array as $element){ $new_data[$element['name']] = $element['value']; } Obviously I can just save out the values, like $name = $element['name'] --- but I was just wondering if there was a more efficient way to do it? Cheers, PS. I tried encapsulating with {} - i.e. $new_data[{$element['name']}] --- but that also fails. guys please help, i have an array(52,51,52) here i want to insert first & last elements into DB, not second one does not follows the series another array (52,52,53) in this case insert first 2 elements into DB since last element does not follow the series. how is this possible? I can't for the life of me understand how to perform this so I need some professional help here. I have a large array that contains some garbage every Nth and Nth + 1 element that needs to go away. array_filter doesn't work with keys but anyhow, i wouldn't know how to design the function. My keys are numeric, starting from 0. The keys I want to remove are part of this sequence: 8, 9, 18, 19, 28, 29 ... Can someone help me design a generic function to remove these keys? function filter_keys($array, $n, $offset) {} $new_array = filter_keys($array, 10, 8 ); I would maybe have to run this function twice, once for 8 offset and once for 9 offset. I am trying to write a dirty script that removes duplicate rows from a multidimensional array. I want to be able to edit the function and spit the duplicates out to a CSV file. Here is my test file: $fullArray = array(array('Jim', 'Jones'), array('Pete', 'Pumpkin'), array('Barak', 'Obama'), array('Jason', 'Newstead'), array('Toby', 'Keith'), array('Jim', 'Jones'), array('Jim', 'Nelson')); echo "<h1>Original</h2>"; for($i=0; $i<count($fullArray); $i++) { echo $fullArray[$i][0] . " " . $fullArray[$i][1] . "<br />"; } echo "<h2>Checked</h2>"; $cleanArray = array(); $cay = array(); $nn=0; $dup=0; // Loop the entire input array foreach ($fullArray as $index => $item) { echo "foreach index:$index<br>"; // Start an internal pointer for ($f=0; $f<count($fullArray); $f++) { echo "for $f "; // if the index is lower or the same as the pointer, skip it to cut down on time if ($f > $index) { // if the rows are the same... if($fullArray[$f][0] == $item[0] && $fullArray[$f][1] == $item[1]) { echo "$item[0] DUP<br>"; // remove it from the array $cay = array_push($cleanArray, array($item[0], $item[1])); array_pop($fullArray[5]); $dup++; } else { // not a duplicate echo " not a dup<br>"; } } else { echo "ON THIS ONE<br>"; } } echo "<br><br>"; } echo"<br>$dup duplicates found<br><br>"; print_r($fullArray); echo "<br /><br>"; // print_r($item); print_r($cleanArray); ?> When I spit out the new fullArray variable, it still has an element from the duplicate record. This is what I get for the output of the full array after the duplicate was removed: Quote Array ( => Array ( => Jim [1] => Jones ) [1] => Array ( => Pete [1] => Pumpkin ) [2] => Array ( => Barak [1] => Obama ) [3] => Array ( => Jason [1] => Newstead ) [4] => Array ( => Toby [1] => Keith ) [5] => Array ( => Jim )[/b] [6] => Array ( => Jim [1] => Nelson ) ) So, I am making a system that shows if there are new posts or not. How I have it done is a singular array called "Read" will have all of the IDs of the read posts. It is entered in the database like so: $ID2= $_SESSION['UserID']; $ID2 = mysql_real_escape_string($ID2); $Readornot=mysql_query("SELECT * FROM forum_read WHERE Reader_ID='$ID2'"); $Readornot2=mysql_fetch_array($Readornot); if($ID2==0) { } else { if(empty($Readornot2)) { $Read1= array("Read" => $Get_TopicID); $Read2 = implode('-',$Read1); mysql_query("INSERT INTO forum_read (Reader_ID,`Read`) values ('$ID2','$Read2')") or die(mysql_error()); } else { $cr_topicid=$Readornot2['Read']; if(strpos($cr_topicid,'-')) { $cr_topicid=explode('-',$cr_topicid); if(!in_array($Get_TopicID,$cr_topicid,true)) { $Read0=implode('-',$cr_topicid); $Read1= array("Read" => $Read0, $Get_TopicID); $Read2= implode('-',$Read1); mysql_query("UPDATE forum_read SET`Read`='$Read2' WHERE Reader_ID='$ID2'") or die(mysql_error()); } } else { if($cr_topicid==$Get_TopicID) { } else { $Read1= array("Read" => $cr_topicid, $Get_TopicID); $Read2= implode('-',$Read1); mysql_query("UPDATE forum_read SET`Read`='$Read2' WHERE Reader_ID='$ID2'") or die(mysql_error()); } } } } It all works fine and dandy to the point where if it's in the database an icon will be black and white, and if its not it wont, signifying read or unread. What I need to do, however, is make it so when there is a new post, it takes all of the entries in the database with the topic ID out of the database, and strips the one part. What I thought of at first was to use str_replace to replace "-" . $TopicID . "-" with "-" But of course, that won't work, because the very first entry could be the topic ID, so it would just be $TopicID- and not -$TopicID- in the database. So, how would I go about doing this? |