PHP - Creating An Array To Make A Graph (math)
I have the following code:
Code: [Select] private function buildJSResponse(){ $data = ""; $i = 0; $arr = array(); while($this->db->row()){ $arr[] = (int)$this->db->field("average"); } $this->max = max($arr); $this->min = min($arr); $this->mid = round(($this->max + $this->min) / 2); foreach($arr as $val){ $nTime = ($val / $this->max) * 100; $data .= "data[$i] = ".$nTime.";"; $i++; } return $data; } It takes an array, finds the max/min and number halfway between the min/max. The next part I am not sure what to do. I am making a line graph using the canvas, so I am building a javascript array, which will contain the point on the chart. The problem I am having, is location. Lets say $max = 110, and $min = 95. the y position on the graph should be 0 for $max, and 100 for $min, then all the other points need to fall into their place as well. $nTime is supposed to do that, but it doesn't any suggestions? The attachment is the result I am getting from my above code. As you can see the lowest number is 49, so the value with 49 should touch the bottom, which it doesn't. Similar TutorialsCode: [Select] if ($user['amount'] >= 15.00){ $user['max_stars'] = 3; } Ok and Code: [Select] if ($user['amount'] >= 20.00){ $user['max_stars'] = 4; }How can I write a function that will loop through the 15,20,25,30,35, all the way up to 600$ or if the max_Stars get's up to 80? I really don't want to have 80 if functions in my code :\ Having to go into somebody else's code yet again! Gah! Originally the totaling page just subtracted a flat discount. But now the client wants to be able to subtract percentage discounts and 'per item' discounts. In the discount table I added a field to determine whether the discount chosen is to be applied as flat off total, flat per item, % off total, and % off each item. I also entered a field that can have a class id, in case this discount is only for that class. (the intention being that otherwise the discount is on anything) I've got a session variable that generates something like : Array ( [217] => 1 [215] => 2 ) meaning 1 person in class #217, and 2 people in class 215. $_SESSION['s_to_be_added'] = array_filter($_POST['participantqty']); Then on the page I'm concerned with, I've been trying to write the script. I know I still need some math stuff figured out But how do I take the array, do the math, and then generate an overall cost for the whole thing? and this is just the discounting? I don't even have a clue how to work in delimiting it if there's a class id.. did any of that make sense? Code: [Select] <?php // the above is the array I want to use to $passed_array = array_filter($_SESSION['s_to_be_added']); // this is the discount 'code' the user entered. $discount = mysql_escape_string($_POST['discount']); // just a donation added after everything. $donation = mysql_escape_string($_POST['donation']); // finding the discount that matches the discount 'code' entered. $query_selectAllItems_events = "SELECT discount_amount,discount_type,workshop_link_1 FROM tbl_discount where discount_value = '$discount'"; $result_all_events = mysql_query($query_selectAllItems_events); $numRows_all_events = mysql_num_rows($result_all_events); $num=mysql_num_rows($result_all_events); $z_row = mysql_fetch_array($result_all_events); // this is just a number: 1, 20, 90 etc. $discount_amount = $z_row['discount_amount']; /*this is 1,2,3,4 - for each type of discount 1- flat 2- flat per item 3- discount on all, 4- discount per item */ $discount_type = $z_row['discount_type']; // the workshop id if the discount is onlyh for this workshop $discount_link_1 = $z_row['workshop_link_1']; // just a description $discount_name = $z_row['discount_name']; if ($discount_type ==1) { /* flat discount on total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total - $discount_amount); $final_total = ($final_total + $donation); } elseif ($discount_type ==2)) { /* discount per item total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total - $discount_amount); $final_total = ($final_total + $donation); } elseif ($discount_type ==3)) { /* percentage discount on total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total * ($discount_amount/100)); $final_total = ($final_total + $donation); } elseif ($discount_type ==4)) { /* percentage discount per item here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total * ($discount_amount/100)); $final_total = ($final_total + $donation); } ?> I have to take over somebody else's project. So I have the combination of being a beginner, not understanding their code well, and not experienced with arrays. I'm in over my head. I have an array passed to the page, that would be something like this: Array ( [215] => [213] => 1 [212] => 2 [214] => ) the user chose 1 person in 213, and 2 people in 212 and I basically need to break it apart to do math like this: (#people x cost of 213 = totalcostA ) + (# people x cost of 212 = totalcostB) = total The broken down data goes into the database, and the total is used for the cart. I've taken suggestions and gotten to this jumbled mess: Code: [Select] $ids = $_POST['workshop_id']; print_r($_POST['participantqty']); // the above shows the arrays are sending to this page and printing correctly: Array ( [215] => [213] => 1 [212] => 2 [214] => ) foreach ($_POST['workshop_id'] as $id){ $qty = $_POST['participatqty'][$id]; } if(sizeof($_POST['workshop_id'])) { // loop through array $number = count($ids); for ($i=0; $i<=$number; $i++) { // store a single item number and description in local variables $itno = $ids[$i]; $qty_insert = $qty[$i]; $query_insertItemWorkshop = "INSERT INTO tbl_registration_workshop (registration_id, workshop_id, regworkshop_qty) VALUES ('$reg_id', '$itno', '$qty_insert')"; $dberror = ""; $ret = mysql_query($query_insertItemWorkshop); $query_selectAllItems_events = 'SELECT * FROM tbl_workshops where workshop_id = '.$itno; @$result_all_events = mysql_query($query_selectAllItems_events); @$numRows_all_events = mysql_num_rows($result_all_events); @$num=mysql_num_rows($result_all_events); @$z_row = mysql_fetch_array($result_all_events); // I want the below to work, but it won't until I can figure out how to break it all down. $qty_total=$qty_insert*$z_row['workshop_price']; $total = $total + $qty_total; if ($ids[$i] <> '') { // I want the info to also appear below, but can't until I figure out how to break them down. echo $total_students; echo "<tr><td valign=top><b>Description:</b> ". $z_row['workshop_title'] ."</td><td align='right' colspan='2' width=300 valign=top>" . $qty_insert . " at ". $z_row['workshop_price'] ." each: </td><td valign=top> $". $qty_total ."</td></tr>"; I am retrieving values in form of array from a database table and out of the I have to build multidimensional array depending upon the parent->child relationship in the same array. The result is as => Array ( => Array ( [label] => Shirt [uri] => # ) [1] => Array ( [label] => Jeans [uri] => # ) [2] => Array ( [label] => Lowers [uri] => # ) [3] => Array ( [label] => T-Shirts [uri] => # ) [4] => Array ( [label] => cotton shirt [uri] => # ) [5] => Array ( [label] => Trousers [uri] => # ) ) each is related to some parent-id. Can any body me any idea.
My longest post of the year..... (thank you in advance for scrolling 😀) Array ( [newQuantity77777] => 3 [newPrice77777] => 5.00 [usedQuantity77777] => 1 [usedPrice77777] => 3.99 [total77777] => 18.99 [newQuantity88888] => // sometimes empty [newPrice88888] => [usedQuantity88888] => 4 [usedPrice88888] => 12.00 [total88888] => 48.00 [newQuantity44444] => 2 [newPrice44444] => 4.00 [usedQuantity44444] => 0 [usedPrice44444] => 3.99 [total44444] => 8.00 // these values I don't need [date] => July 25 2021 // these values below I don't need [address] => 123 Anystreet Avenue [address2] => [zipcode] => 90210 [city] => Beverly Hills [state] => CA [planet] => Mars ) I've been trying to use that array to create a special "sub-array" for only the SKU numbers and just their new and used quantities and prices. DESIRED RESULT: Array ( [77777] => Array ( [newQuantity] => 3 [newPrice] => 5.00 [usedQuantity] => 1 [usedPrice] => 3.99 ) [88888] => Array ( [newQuantity] => 0 [newPrice] => 0 [usedQuantity] => 4 [usedPrice] => 12.00 ) [44444] => Array ( [newQuantity] => 2 [newPrice] => 4.00 [usedQuantity] => 0 [usedPrice] => 3.99 ) ) Knowing that my SKU numbers are always exactly 5 digits, and no other $_POST keys will ever have 5 digits, I've been able to accomplish this with horribly convoluted and unsatisfactory code like this: $sku = array(); foreach($_POST as $var => $val) { $number = substr($var,-5); if (preg_match("/\d{5}/",$sku)) { $sku[$number] = // the array keys will be the SKU numbers // then I keep looping to look for the string "newQuantity" // capture that value... and create little mini arrays // for my big multidimensional array..... Is there a better way to go about this? Thank you. Given array Code: [Select] Array ( [Post] => Array ( [title] => new with has many through for tags [body] => hello tags [category_id] => 11 [tags] => one two three [mark] => 1 ) ) I need to make an array something like this: Code: [Select] Array ( [Post] => Array ( [title] => new with has many through for tags [body] => hello tags [category_id] => 11 [mark] => 1 ) [Tag] => Array ( [0] => Array( [name] => one ) [1] => Array( [name] => two ) [2] => Array( [name] => three ) ) ) How can i make it? Hi. I need some help working something out. I have an array that has all the numbers from, 0 to 9. What I want to do is loop through the array to make all the combinations possible up to a string thats 255 chars long. $array = array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ); Should be looped through to create strings like this: Code: [Select] 0 1 2 3 4 5 6 7 8 9 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 etc.. Just as if it's counting. Hello I was trying from days to create an array from a txt file by i can't make it happen. I am so desperate now and i want your help guys The code create a txt file from a textarea feild after it's submited each on a line. After that the php code need collect these data from the txt file and create an array from them. Example: if i type in the textarea: test test1 test2 I want these usernames to be inserted in the array so it would be like this: $names = array('test','test1','test2'); Anyone can help me This is the code <html> <head> <title></title> <style type="text/css"> body{ background-color:#1166aa; } #mainbox{ width:inherit; background-color:#FFFFFF; padding:14px; border:solid 3px #000000; float:left; } #mainbox2{ background-color:#CCCCCC; border:solid 2px #000000; padding:11px; } #contaner{ border:solid 0px #00FF00; } h1:hover{ color:#0000CC; cursor:pointer; } #msg{ cursor:pointer; } table td{ border-top:outset 1px #999999; } #amount{ color:#FF0000; cursor:crosshair; } #to{ color:#3300FF; } #from{ color:#3300FF; } #subject{ color:#3300FF; } </style> </head> <body alink="#003399" vlink="#003399"> <?php ///////////////////////////////////////////////// function create_list(){ $list= ($_GET ['name_list']); $file= "list.txt"; $file_pointer = fopen($file ,'w'); fwrite($file_pointer , $list); fclose($file_pointer); } ////////////////////////////////////////////////// $list= ""; create_list(); ////////////////////////////////////////////////// function explodeRows($data) { $rowsArr = explode("\n", $data); return $rowsArr; } $filename = "list.txt"; $handle = fopen($filename, 'r'); $data = fread($handle, filesize($filename)); $rowsArr = explodeRows($data); for($i=0;$i<count($rowsArr);$i++) { $name = explodeRows($rowsArr[$i]); function name(){ $names = array('the usernames submited to be inserted here','the usernames submited to be inserted here',.......); } } //////////////////////////////////////////////////// if ($_GET ['submit'] == "submit"){ create_list(); name(); } ?> <script type="text/javascript"> function foo(textarea,limit){ var val=textarea.value.replace(/\r/g,'').split('\n'); if(val.length>limit){ alert('You can not enter\nmore than '+limit+' lines'); textarea.value=val.slice(0,-1).join('\n') } } </script> <table align="center" id="contaner"> <tr><td> <form action="<?php $_SERVER [SERVER_NAME]; ?>" method="get"> <div id="mainbox"> <div id="mainbox2"> <table> <tr> <td>name List :</td> </tr> </table> <textarea id="name_list" name="name_list" cols="60" rows="9" onkeyup="foo(this,50)"></textarea> </div> <tr> <td><center><input name="submit" type="submit" value="submit"/></center></td> </tr> </div> </form> </tr></td> </table> </body> </html> Alright, this has been puzzling me for a while now and I think it's time I seek help before my brain turns to mush. I've been modifying a PHP text based game called Legend of the Green Dragon to add more functionality, etc. One of the things I want to add is the ability to add levels higher then 15. The original array looks like this: $exparray = array(1=>100,2=>400,3=>1002,4=>1912,5=>3140,6=>4707, 7=>6641,8=>8985, 9=>11795,10=>15143,11=>19121,12=>23840, 13=>29437,14=>36071,15=>43930, ); Now, I could just hardcode each level, but noo, I want to be able to do it from a module type thing from the admin panel (which I've already gotten that working gratefully) so I've tried writing a few different scripts to take the information from the MySQL database and turn it into an array like above but I've gotten completely lost. This is what I currently have: $expsql = "SELECT * FROM " . db_prefix("myolevels"); $numrows = mysql_num_rows($expsql); for ($i = 1; $i <= $numrows; $i++) { $expresult = mysql_query($expsql); while ($rows = mysql_fetch_assoc($expresult)) { $exparray = array($i=>$rows['myoexpreq']); } } Although when I call the array, it always returns null for the myoexpreq causing your master to look for you all the time (forcing level up when it shouldn't be). Is there any way to create an array like the first with SQL? Thought this might help as well: PHP Warning: "Variable passed to each() is not an array or object" in /home/ileetcom/public_html/logd/lib/experience.php at 35. Call Stack: 2: each(NULL) called from /home/ileetcom/public_html/logd/lib/experience.php on line 35 3: exp_for_next_level(16, "0") called from /home/ileetcom/public_html/logd/village.php on line 131 I have a array for example: Code: [Select] $item = array( "Great <em>Bittern</em>"=>"Botaurus stellaris", "Little <em>Grebe</em>"=>"Tachybaptus ruficollis", "Black-necked Grebe"=>"Podiceps nigricollis"); which will output Code: [Select] Array ( [Great Bittern] => Botaurus stellaris [Little Grebe] => Tachybaptus ruficollis [Black-necked Grebe] => Podiceps nigricollis ) how can I input data from a database so it comes out as the array assuming I have $row[3] and $row[0] as the data? for example Code: [Select] while($row=mysql_fetch_array($result)){ //$item.=array($row[3],$row[0]); //array_push($item,array($row[3]=>$row[0])); //$item.=array($row[3]=>$row[0]); $item.="[".$row[3]."]=>".$row[0]; } which of course doesnt work?? All I am not the best at PHP and have been trying to work out how to make a treeview from an array. I managed to get as afar as populating my array as i would like and I can get those values back but now im really stuck What id love to be able to do is use my area field as the parent and my title field as the child and have a counter on the parent with no of child nodes. If someone can help me out with that bit id be really greatful, as I ve already sorted my javascript etc this is my last problem and its driving me nuts Many Thanks for looking and i really do appreciate any help Gibbo <?php $row = 0; $myarray = array(); foreach ($view->result as $result) { $arg = $view->render_field('field_decision_type_value', $row); $arg2 = $view->render_field('title', $row); $myarray[$row]["area"]=$arg; $myarray[$row]["title"]=$arg2; $row++; } asort($myarray); $last = count($myarray) - 1; $rowcount=0; while ($rowcount <= $last) { print $myarray[$rowcount]["area"]; print $myarray[$rowcount]["title"].'|<br />'; $rowcount++; } ?> I have a simple detection for mobile devices and it works fine but it has gotten a bit bloated so I tried to put the list in an array. I don't get errors but it doesn't work. Here is what I tried $useragents = array("iPhone","iPod","incognito","webmate","Android","dream","CUPCAKE","blackberry9500","blackberry9530","blackberry9520","blackberry9550","blackberry 9800","webOS","s8000","bada","Googlebot-Mobile"); if (in_array(1, $useragents)) { $phones = strpos($_SERVER['HTTP_USER_AGENT'], $useragents); } if ($phones == true) { include_once './template/phones.php';} Please assist Hi guys, Is there an html code that allows you to array a form input? and once you passed the form, how do you extract the data then insert it to the database? Thanks I need to extract shopping cart transaction information from a database, convert it to json format and send to another DB. Because the fields are not a direct match the calculated values are first bing put into variables. I'm extracting the line items from the database into an array and looping through the array to get each line item which I want to then insert into another array as a sub array. By the way, I'm new at PHP so be gentle. The first step I've coded as: Code: [Select] foreach ($oit_array as $inner1) { // Check type if (!is_array($inner1)) {$inner1 = array($inner1);} $lineprice+=$inner1[orderitem_price]; //calculate amounts required in variables $linepriceinc=$inner1[orderitem_price]+($inner1[orderitem_tax]/$inner1[orderitem_quantity]); if($inner1[orderitem_tax]==0){$linetaxrate+=0;} else $linetaxrate=($inner1[orderitem_final_price]-$inner1[orderitem_tax])/$inner1[orderitem_tax]; $linetaxtotal+=$inner1[orderitem_tax]; $orderqty+=$inner1[orderitem_quantity]; $productname=$inner1[orderitem_name]; $qtyshipped+=$inner1[orderitem_quantity]; $totallineamount+=$inner1[orderitem_final_price]-$inner1[orderitem_tax]; $totallineamountinc+=$inner1[orderitem_final_price]; $unitofmeasure="Units"; $linearray[] = array("LinePrice"=>$lineprice, "LinePriceInc"=>$linepriceinc, "LineTaxCode"=>"GST", "LineTaxRate"=> $linetaxrate, "LineTaxTotal"=> $linetaxtotal, "OrderQty"=> $orderqty, "ProductName"=> $productname, "QtyShipped"=> $orderqty, "TotalLineAmount"=> $totallineamount, "TotalLineAmountInc"=>$totallineamountinc, "UnitOfMeasure"=>"Units"); I then reference the array as $linearray as follows: Code: [Select] //Create Array $salesarray= array ("type"=> "TCashSale", "fields"=>array ("CustomerName"=>$customername, "ShipToDesc"=>$shiptodesc, "Lines"=> array("type"=> "TCashSaleLine", "fields"=> $linearray)), "SalesPayments"=>array("type"=>"TSalesPayments", "fields"=>array("Amount"=> $amount, "PayMethod"=> $paymentmethod))); The problem that I have is that the resulting array contains square brackets around the "linearray" data like so: Code: [Select] {"type":"TCashSale","fields":{"CustomerName":"Cash Customer","ShipToDesc":"Rod Farrell\n\r1234 Short St\n\r\n\rSlackville Queensland 4001","Lines":{"type":"TCashSaleLine","fields":[{"LinePrice":54.54545,"LinePriceInc":54.54545, What am I doing wrong?? Hi guys, I'm still stuck on making this multi-level drop down menu, so I figure that I'll listen to how you guys would do it. I don't necessarily need any code, but just ideas on how to code it. Basically, I need it to store each item in a database. It needs to: be accessed, processed, and formatted with PHP end up returning either a multi-dimensional array, or the raw HTML. Examples: Code: [Select] <?php array( array( 'label'=>'Test', 'link'=>'index.php?r=test', 'sort'=>0, 'children'=>array(--blah blah blah--) ), array(--blah blah blah--) ); Code: [Select] <div id="menu"> <ul> <li><a href="index.php?r=test"><h2>Test</h2></a> <ul> <li><a href="blah">Blah</a> <ul> <li><a href="blah">Blah</a></li> </ul> </li> </ul> </li> </ul> </div> That's pretty much it. If you have any ideas or suggestions, please feel free to help me out. Thank you guys! I have four different arrays and I want to place them into a multi dimensional array and then I want to place it into a Session variable. This is what I have below.How do I do this? when I print_r($_Session) I don't get anything just option[](2); Code: [Select] $_SESSION ['option']['green'] = array('name '=>'jeff'); $_SESSION ['option']['red'] = array('name '=>'mary'); $_SESSION ['option']['blue'] = array('name '=>'joe'); $_SESSION ['option']['brown'] = array('name '=>'ash'); Hi, I want to develop array like following Code: [Select] $BCD=array('type' =>'TYPE1', array( 0=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 1=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 2=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 3=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), ) )); I have written following code to achieve the same but not getting result. Code: [Select] $sql = "select * from tablename "; $result = mysql_query($sql); $k=0; while ($row = $db->mysql_fetch_array($result)) { // array_push($BCD['type'],$row['type']); $BCD1=array('type' =>$row['type'], array( $k=>array('column1'=>$row['column1'],'column2'=>$row['column2'],'column3'=>$row['column3'],'column4'=>$row['column4'], 'column5'=>$row['column5'],'column6'=>$row['column6'],'column7'=>$row['column7']) )); $k++; } hi guys ..I want to create graphs in php. Data will be taken by mysql ofcourse... I have seen lots of options like fusion chart xml, phpgraphlib and so on... my question is What will be the best library or tool. What will be your recommendation to create graphs. Thanks Hi All, Are there any decent PHP graph solutions out there? I have an SQL statement that returns 12 numberical values in an array (mssql_fetch_array). I would like to plot these values on a graph. Thanks Matt I'm trying to create a website, that echo's out a bunch of groups, where each group contains a group of checkboxes, containing A value, and a label for the checkbox, the way it is created right now, is foreach that echo's out a bunch of php arrays, which was easier than the static way before - But still, it's static in some way, or not very user friendly at the moment.. My problem is that I really want to write it in a database when I have the option. Is there anyone that can give some tips how to do? At the moment, my foreach looks like this: Code: [Select] echo '<form method="post" action="'.$_SERVER['PHP_SELF'].'">'; /* NEXT WE CREATE OUR FOREACH LOOPS TO ECHO THE HTML FOR LOOKS AND CHECKBOXES */ $totalID=0; // this is a counter we use to build our check box names foreach ($items as $list){ $totalID++; // add one to the checkbox name counter echo "<h2>{$list['title']}</h2>\n"; // and echo out our section header foreach ($list['items'] as $cbox){ // now for each item in the list, call it $cbox // $cbox now holds the item name, and point value echo "<label class='checkbox'><input type='checkbox' name='totals[$totalID][]' value='{$cbox[1]}'> {$cbox[0]}</label>\n"; } } echo "</form>"; And my array is something like this: Code: [Select] $items['computers']['title']='Computer Brand'; $items['computers']['items'][]=array('Apple iMac',1); $items['computers']['items'][]=array('Apple Macbook',.5); $items['phones']['title']='Phone Brand'; $items['phones']['items'][]=array('iPhone',1); $items['phones']['items'][]=array('HTC',1); As said, I can write this, but takes time. I want to get it into a database, that data above, but I'm having problems about echo'ing it out, I really can't see how I should do. My current database looks like this: Thank you! |