Using key function without overwritting the same keys in PHP - php

I'd like to extract the data from an array within an array. But the problem is, when I use the key function it overwrites the first entry. I'm expecting to have a result of 135 rows, but it only gives me back 114.
Below is the code where I'm getting a problem..
while($row1 = mssql_fetch_array($result1)) {
$mycount = $mycount + 1;
$boskey = $row1["EAN11"]."^".$row1["AUART"];
$boskey1 = $row1["ORDNUM"]."^".$row1["ERDAT"]."^".$row1["KUNAG"]."^".$row1["NAME1"]."^".$row1["PERNR"]."^".$row1["FKIMG"]."^".$row1["BASEPRICE"]."^".$row1["NETPRICE"]."^".$row1["ZZMAXDISC"]."^".$row1["MVGR1"]."^".$row1["KDGRP"];
$bos[$boskey][$boskey1] = $bos[$boskey][$boskey1];
}
for ($i = 0; $i < count($bos); $i++) {
$abc = key($bos);
$arr = explode("^",$abc);
$ean11 = $arr[0];
$auart = $arr[1];
echo $ean11 . " - " . $auart;
for ($j = 0; $j < count($bos[$abc]); $j++) { //total count of $bos[$abc] is 114.
$xxx = key($bos[$abc]);
$arr1 = explode("^",$xxx);
$ordnum = $arr1[0];
$docdate = $arr1[1];
$customer = $arr1[2];
$name1 = $arr1[3];
$ae = $arr1[4];
$qty = $arr1[5];
$baseprice = $arr1[6];
$netprice = $arr1[7];
//$discount = $arr1[8];
$booktype = $arr1[9];
$kdgrp = $arr1[10];
$discount = 100 - (100 * ( $netprice / $baseprice));

Related

Switch elements of 2d array

I have a problem: I can't make my script working with penalties, but I made it work with bonuses.
Start: two-dimensional array of users, each has id, name, start position and modificator (if modificator < 0 its bonus; if modificator > 0 its penalty).
How modificators work: for example, I have a queue of users Test1, Test2, Test3. If I give user Test3 bonus 1, he will switch places with user Test 2 and final queue will be Test1, Test3, Test2. If I give him bous 2, than he will be first at queue.
Penalties works the other way around. If I give user Test1 penalty 1, he will be second in a queue. If I give him penalty 3, he will be moved to the end of the queue.
This is my working code for bonuses:
<?
$new = array(); $orders = array();
$new[111]['position'] = 1; $new[111]['user'] = 'Test1'; $orders[1] = 111; $new[111]['shift'] = 0;
$new[222]['position'] = 2; $new[222]['user'] = 'Test2'; $orders[2] = 222; $new[222]['shift'] = 0;
$new[333]['position'] = 3; $new[333]['user'] = 'Test3'; $orders[3] = 333; $new[333]['shift'] = 0;
$new[444]['position'] = 4; $new[444]['user'] = 'Test4'; $orders[4] = 444; $new[444]['shift'] = 0;
$new[555]['position'] = 5; $new[555]['user'] = 'Test5'; $orders[5] = 555; $new[555]['shift'] = 0;
$new[666]['position'] = 6; $new[666]['user'] = 'Test6'; $orders[6] = 666; $new[666]['shift'] = 0;
$new[777]['position'] = 7; $new[777]['user'] = 'Test7'; $orders[7] = 777; $new[777]['shift'] = 0;
$new[888]['position'] = 8; $new[888]['user'] = 'Test8'; $orders[8] = 888; $new[888]['shift'] = 0;
//shift function
function bonus($start, $bonus)
{
global $new, $orders;
//for bonuses, shift to start, $bonus is negative number
if ($bonus < 0)
{
for ($i = $start; $i > ($start - abs($bonus)); $i--)
{
$order_id = intval($orders[$i]);
$prev = intval($orders[$i - 1]);
if ($prev != 0)
{
$temp = $new[$order_id]['position'];
$new[$order_id]['position'] = $new[$prev]['position'];
$new[$prev]['position'] = $temp;
$orders[$i] = $prev;
$orders[$i - 1] = $order_id;
}
}
}
//end for bonuses
}
// Now I set modificator (bonus negative, penalty positive)
$new[555]['shift'] = -2;
// sort by bonuses
$i = 1;
foreach($new as $value)
{
$order_id = $orders[$i];
bonus($new[$order_id]['position'], $new[$order_id]['shift']);
$i++;
}
// sort 2d array with field position
usort($new, function($a, $b){
return $a['position'] <=> $b['position'];
});
//DATA OUTPUT
$i = 1;
foreach($new as $value)
{
echo $i . '. ' . $value['user'] . ' ; shift: ' . $value['shift'];
echo '<br>';
$i++;
}
?>
At this code I set bonus with: $new[555]['shift'] = -2;
So, penalty will be like: $new[444]['shift'] = 3;
Code for penalties I think must be something like this:
//for penalty, shift to the end, $bonus positive number
if ($bonus > 0)
{
$total_new = count($new);
for ($i = $start; $i < ($start + $bonus); $i++)
{
$order_id = intval($orders[$i]);
$next = intval($orders[$i + 1]);
if ($next < $total_new)
{
$temp = $new[$order_id]['position'];
$new[$order_id]['position'] = $new[$next]['position'];
$new[$next]['position'] = $temp;
$orders[$i] = $next;
$orders[$i + 1] = $order_id;
}
}
}
//end code for penalty
Here is something wrong with $orders. I tried many different types of code all day long, including array enumeration in asc/desc order, but it didn't work correcty...
P.S. I know about array_multisort, but I dont need to sort, I need to switch elements with each other.
Again: bonus 2 means that user must switch places with previous number 2 times. Penalty 3 means that user must switch places with next user 3 times.

How to sort associative array by column that contains previous id value?

I have such associative array. The key prev contains a value to match the id value of the previous item.
When prev is 0 then it's the first item.
Correct order should be by index prev:
$data[3]
$data[1]
$data[0]
$data[4]
$data[2]
but I don't know how to achieve this.
$data[0]['id'] = 10;
$data[0]['name'] = 'Zoe';
$data[0]['prev'] = 20;
$data[1]['id'] = 20;
$data[1]['name'] = 'Tom';
$data[1]['prev'] = 40;
$data[2]['id'] = 30;
$data[2]['name'] = 'Andy';
$data[2]['prev'] = 50;
$data[3]['id'] = 40;
$data[3]['name'] = 'Kathy';
$data[3]['prev'] = 0;
$data[4]['id'] = 50;
$data[4]['name'] = 'Barbara';
$data[4]['prev'] = 10;
I think this is what you want to do:
<?php
$data = array();
$data[0]['id'] = 10;
$data[0]['name'] = 'Zoe';
$data[0]['prev'] = 20;
$data[1]['id'] = 20;
$data[1]['name'] = 'Tom';
$data[1]['prev'] = 40;
$data[2]['id'] = 30;
$data[2]['name'] = 'Andy';
$data[2]['prev'] = 50;
$data[3]['id'] = 40;
$data[3]['name'] = 'Kathy';
$data[3]['prev'] = 0;
$data[4]['id'] = 50;
$data[4]['name'] = 'Barbara';
$data[4]['prev'] = 10;
$nextId = 0;
$results = array();
while (count($data) > 0) {
$matchFound = false;
foreach ($data as $key=>$val) {
if ($val['prev'] === $nextId) {
$results[] = $val;
$nextId = $val['id'];
unset($data[$key]);
$matchFound = true;
break;
}
}
if (!$matchFound) break;
}
The outer while loops checks if the $data array still has elements. The inner for loop searches for the array with element 'prev' equal to the $nextId that we are looking for (initially set to 0). When it finds it, it assigns the id to $next, removes the element from the original array, and adds the element to our sorted array.
Do you mean order by "pre"? You want PHP's usort() function:
<?php
$data = array();
$data[0]['id'] = 10;
$data[0]['name'] = 'Zoe';
$data[0]['prev'] = 20;
$data[1]['id'] = 20;
$data[1]['name'] = 'Tom';
$data[1]['prev'] = 40;
$data[2]['id'] = 30;
$data[2]['name'] = 'Andy';
$data[2]['prev'] = 50;
$data[3]['id'] = 40;
$data[3]['name'] = 'Kathy';
$data[3]['prev'] = 0;
$data[4]['id'] = 50;
$data[4]['name'] = 'Barbara';
$data[4]['prev'] = 10;
function my_order($a,$b) {
return $a['prev'] > $b['prev'];
}
usort($data, "my_order");
print_r($data); //Kathy, Barbara, Zoe, Tom, Andy
Using the function "my_order", which compares $data[$x]['prev'] to $data[$x+1]['prev'], you can yield the results sorted by the "prev" values of the array.
You can use PHP's usort function to do so. It takes an array as the first parameter and then a comparison function as the second. From the documentation:
function cmp($a, $b){
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
The comparison function returns 0 if they're equivalent, -1 if a comes before b, and 1 if b comes before a. You can order it however you like.
For you, it could look like:
function cmp($a, $b){
if ($a['prev'] == $b['prev']) {
return 0;
}
return ($a['prev'] < $b['prev']) ? -1 : 1;
}
usort($data, "cmp");
you should try this hope it helps you
$data = array();
$data[0]['id'] = 10;
$data[0]['name'] = 'Zoe';
$data[0]['prev'] = 20;
$data[1]['id'] = 20;
$data[1]['name'] = 'Tom';
$data[1]['prev'] = 40;
$data[2]['id'] = 30;
$data[2]['name'] = 'Andy';
$data[2]['prev'] = 50;
$data[3]['id'] = 40;
$data[3]['name'] = 'Kathy';
$data[3]['prev'] = 0;
$data[4]['id'] = 50;
$data[4]['name'] = 'Barbara';
$data[4]['prev'] = 10;
function sortIt($data) {
$output = array();
$key = array_search(0, array_column($data, 'prev'));
$output[] = $data[$key];
unset($data[$key]);
$data = array_combine(
array_column($data,'prev'),
$data
);
while($data){
$last = end($output);
$output[] = $data[$last['id']];
unset($data[$last['id']]);
}
return $output;
}
echo '<pre>';
print_r(sortIt($data));
You could get a bit better response time using a hash:
foreach($data as $rec) {
$hash[$rec["prev"]] = $rec;
}
$id = "0";
while (isset($hash[$id])) {
$result[] = $curr = $hash[$id];
$id = $curr["id"];
}
See it run on eval.in

How to format an associative array with another structure?

I have a query like this:
select truck, oil_type, km_min, km_max from trucks;
I'm using codeigniter and with the $query->result_array() function so its loaded in an associative array with this structure:
/*
array(
truck
oil_type
km_min
km_max
)
*/
$arr[0]["truck"] = 2;
$arr[0]["oil_type"] = 2;
$arr[0]["km_min"] = 345;
$arr[0]["km_max"] = 567;
$arr[1]["truck"] = 2;
$arr[1]["oil_type"] = 4;
$arr[1]["km_min"] = 234;
$arr[1]["km_max"] = 867;
$arr[2]["truck"] = 1;
$arr[2]["oil_type"] = 2;
$arr[2]["km_min"] = 545;
$arr[2]["km_max"] = 867;
$arr[3]["truck"] = 4;
$arr[3]["oil_type"] = 3;
$arr[3]["km_min"] = 45;
$arr[3]["km_max"] = 567;
Then, I'm trying to restructure it grouping the trucks by the id, something like this:
/*
trucks - array(
truck
truck_data - array(
oil_type
km_min
km_max
)
)
*/
$arr["truck"][0]= 2;
$arr["truck"][0]["truck_data"][0]["oil_type"] = 2;
$arr["truck"][0]["truck_data"][0]["km_min"] = 345;
$arr["truck"][0]["truck_data"][0]["km_max"] = 567;
$arr["truck"][0]["truck_data"][1]["oil_type"] = 4;
$arr["truck"][0]["truck_data"][1]["km_min"] = 234;
$arr["truck"][0]["truck_data"][1]["km_max"] = 867;
$arr["truck"][1]= 1;
$arr["truck"][1]["truck_data"][0]["oil_type"] = 2;
$arr["truck"][1]["truck_data"][0]["km_min"] = 545;
$arr["truck"][1]["truck_data"][0]["km_max"] = 867;
$arr["truck"][2]= 4;
$arr["truck"][2]["truck_data"][0]["oil_type"] = 3;
$arr["truck"][2]["truck_data"][0]["km_min"] = 45;
$arr["truck"][2]["truck_data"][0]["km_max"] = 567;
I thought in something like the code below:
$res = $query->result_array();
$cnt_total = count($res);
$y = 0;
for ($x=0; $x < $cnt_total -1 ; $x++) {
$truck = $res[$x]["truck"];
$trucks["truck"][$y] = $truck;
$q = $x + 1;
$i = 0;
do{
$trucks[$y][$i]["oil_type"] = $res[$q]["oil_type"];
$trucks[$y][$i]["km_min"] = $res[$q]["km_max"];
$trucks[$y][$i]["km_max"] = $res[$q]["km_max"];
$q++;
$i++;
if ($q <= $cnt_total) break;
} while ( $truck === $res["truck"][$q] );
$y++;
}
But does not work properly... I'm too far of the solution? The performance It's important for me in this particular case.
There is a phpfiddle where you can try:
http://phpfiddle.org/main/code/67j-ui5
Any idea, tip, or advice will be appreciated, and if you need more info, let me know and I'll edit the post.
Try this:
$res = $query->result_array();
$trucks = array();
foreach ($res as $row) {
$truck["truck"] = $row["truck"];
$truck["truck_data"] = array(
'oil_type' => $row["oil_type"],
'km_min' => $row["km_min"],
'km_max' => $row["km_max"],
);
$trucks[] = $truck;
}
var_dump($trucks);
What you've provided as a desired result is a little ambiguous. This might give what you're asking for.
$trucks=array();
$res = $query->result_array(); // assuming this is actually several trucks
foreach ($res as $r){
// set up the array from the data without writing out every column manually
$truck=array(
'truck'=>$r['truck'],
'truck_data'=>$r,
);
// remove the bit you wanted separately as 'truck' from 'truck_data'
unset($truck['truck_data']['truck']);
// push into $trucks
$trucks[]=$truck;
}
Is this what you need? conversion result is stored in $result
$result = array();
foreach($query->result_array() as $truck)
{
$new_truck = array();
$new_truck['truck'] = $truck['truck'];
$new_truck['truck_data'] = array();
$new_truck['truck_data']['oil_type'] = $truck['oil_type'];
$new_truck['truck_data']['km_min'] = $truck['km_min'];
$new_truck['truck_data']['km_max'] = $truck['km_max'];
array_push($result, $new_truck);
}

Sum the value of variable return by for loop in php

I have this code that is working perfectly. My question is how can I sum all the value of $manpowerCost and $otherCharges?
for ($i = 1; $i<=9; $i++) {
$m = '0'.$i;
$sumMc = array();
$revenue = revenue($project, $year.'-'.$m);
$manpowerCost = manpowerCost($project, $year.'-'.$m);
$otherCharges = otherCharges($project, $year.'-'.$m);
$netIncome = netIncome($revenue, $manpowerCost, $otherCharges);
if ($manpowerCost<=0 && $m <= $projected_date){
$manpowerCost = round(($projected_mc * $percentage_mc),2);
$projected_total_mc += $manpowerCost;
$pt = $pt + $manpowerCost;
} else {
$projected_mc = $manpowerCost;
$manpowerCost = $projected_mc;
}
if ($otherCharges<=0 && $m <= $projected_date){
$otherCharges = round(($projected_oc * $percentage_oc),2);
$projected_total_oc += $otherCharges;
$pt = $pt + $otherCharges;
} else {
$projected_oc = $otherCharges;
$otherCharges = $projected_oc;
}
echo '<td>RE:'.number_format($revenue, 2, '.', '').'<br />MC:'.number_format($manpowerCost, 2, '.', '').'<br />OC:'.number_format($otherCharges, 2, '.', '').'<br />NI:'.$netIncome.'</td>';
}
U can Try like this
$powercost_total = '0';
for ($i = 1; $i<=9; $i++) {
$manpowerCost = manpowerCost($project, $year.'-'.$m);
$powercost_total = $manpowerCost + 4powercost_total;
....
Declare $TotalManPowerCost and $TotalOtherCharges variables outside of the loop, and add $manpowercost and $otherCharges to them in each iteration of the loop

php uncompress & unpack gives array containing a few (9 in 10309) undefined values

I have a binary data string that i uncompress and unpack into an array using php with the following code (complete code for this php page is included at the bottom of this question):
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$glycopeptide[$hits] = $row[1];
echo $row[4];
// $row[4] contains the binaryString
$mz = base64_decode($row[4]);
$unc_mz = gzuncompress($mz);
$max = strlen($unc_mz);
$counter = 0;
for ($i = 0; $i < $max; $i = $i+4) {
$temp = substr($unc_mz,$i,4);
$temp = unpack("f",$temp);
$mz_array[$counter] = $temp[1];
$counter++;
}
$hits++;
}
I find that both the mz_array (the above code, X-coords) has 9 undefined values (all at the end) but that the int_array (similar code, Y-coords) also has 9 undefined values (distributed throughout the whole array (not grouped or at the beginning/end).
Here is an example of a small testing chunk that I added to my page:
Test code:
for ($i = 0; $i < $counter; $i++) {
echo $i;
echo " - ";
echo $mz_array[$i];
echo " - ";
echo $int_array[$i];
echo "<br/>";
}
A "selection" of the output (Note the missing values):
671 - 274.20001220703 - 429
672 - 274.39999389648 -
673 - 274.60000610352 - 1098
-- skipping a few lines --
10299 - 2199.8000488281 - 0
10300 - 2200 - 0
10301 - - 0
10302 - - 0
The weirdest part is that if i manually enter the strings in the complete/original code (see bottom of page) I get the undefined values while if I manually enter the string that is returned by doing "echo $row[4]" (contains the binaryString) in the following code it yields no undefined values.
<?php
$string = " /* Copy the string in the spoiler (on this page) here */ ";
$int = base64_decode($string);
$unc_int = gzuncompress($int);
$max = strlen($unc_int);
$counter = 0;
$max_int = 0;
for ($i = 0; $i < $max; $i = $i + 4) {
$temp= substr($unc_int,$i,4);
$temp = unpack("f",$temp);
$int_array[$counter] = $temp[1];
echo $counter;
echo " -- ";
echo $int_array[$counter];
echo "<br/>";
$counter++;
}
?>
Does anyone have any suggestions or idea's why this might occur?
PS: Can someone add the tag gzuncompress? (I don't have the reputation for it).
EDIT 1
I have included an example binaryString (WARNING: Huge!)
Y-Coords (retrieved by the commented echo $row[4] in the code):
eJztXQuQFMUZblQEQfEQUQSJYwRBSuLG+AAFHdmeRYOPS2lRgEgNvgpLhUuQkooYB5GXBLIaHwRQRwMpCqOuiciJhU4KjUoMnm98r2KUaKkXreBpSCXf3z3Lzu7Na3fn9nZhvqop2N2enu6///7fPcdYjBgxYsSIESNGjBhVgvFGkqmLOWPjk77tlNs5a35AY9kdnBlPo+3GMZ5tm87VmDULfXL/PnOwzkGfP0P7RLj2MUrAaNB0l2OtJuDzVu+188XJnKmnYZ0a5DpZE7Fu3TVm/BOft5TZZ4yqwvwf1u+ne89ea7wM/Pke5vvI3jHfGGVA56xxEnTWKeCT/h588i5k3cEp1vyuxtQN+H/an5+ya9GuBf2t6zi+s2ZAHh/KC+V7BTDXoK/15Y03uxD3zo1urmoKND4efXb17tPqgTZz0OYy/+eaB2uMHYP1UKOjV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S45H/0hLmu0XGKGon58e8fvP7ULaPC4d33EbmTBVwei7SEydyj86Ffb62x1Yek6JweRO6mWzRcAqjvSH8d+erG9z+ELt7j7BvT1iZ0zc8TqyZ9TH/X3e1zHNj9Zc7mkGBECezHovZKegMwXccMw9lud6nfDeVbEicH2WZdSztXsSUhwz/dpVRPZD+xYVdD7JNqSsq7rLp8xU13s3NrwDWsRdG6q4pqZHIh3cFHdZ4FsqAY/Xcs9zxd1JuhcsMg5OM9jefC119ke5bXy6+zCgPJPmW5a4RnXHXYNW1TA+mTn82jfCxcG9PcDyH4e3gm8QTKn2M6i3M/RkG9t8CmWyZiXsN8c8knUSt1Ze7y8N0DUH5R5ZqSusML++xt7SCyazqQYr/Hy63RcYK0riqnWGyZGkPMf7VIfRqin9yxXE2SLmp1vQ5cD8ovS52rMPFNjVgTn8mN0LoTsqpH3uO/poNxeZH5UB8D6MZfngMvV998G5BMTdl1gBfrGOoTLOqw9PDbZcIQm/uZIqPe3Ua6wjt6rGRpkY+8NdnZnoMz30e2poPNzIl/rst+MBSFyV27IFMbYqR+j1T67sJci009jjbdo8t3ZPnk48e5RF79KvLOkBurFax3qlZxlNxbl/SBL0/SuruMr08H1DuVvVa79ixEjRowYMWJUDeZHnFln188ZphgxYsSIESNGjBgxYsSIESNGjBgxooB473oF783vaDT11Vj2njJz7jFixOhwiL/PuDE+Mxej5vF/owjA3A==
Complete code:
<?php
require 'phplot/phplot.php';
$type = $_GET['type'];
$gp = $_GET['gp'];
$site = $_GET['site'];
$prec = $_GET['prec'];
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db('leidenGlycoPeptide') or die ();
$query = sprintf("select precursor.mzValue, glycoPeptide.protein, binaryDataArray.arrayLength, binaryDataArray.encodedLength, binaryDataArray.arrayData, precursor.chargeState, run.pepMass, run.PepSeq from glycoPeptide, spectrum, binaryDataArray, run, precursor where run.glycoPeptide = glycoPeptide.id AND spectrum.run = run.id AND precursor.run = run.id AND binaryDataArray.spectrum = spectrum.id AND precursor.id = spectrum.precursor AND spectrum.spectrum like 'm/z' AND precursor.mzValue like '%s' and glycoPeptide.protein like '%s' and run.glycoSite like '%s' and run.glycoType like '%s' ORDER by glycoPeptide.protein, spectrum.spectrum",(string)$prec, (string)$gp, (string)$site, (string)$type);
$result = mysql_query($query);
$hits = 0;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$charge = $row[5];
$pepmass = $row[6];
$pepseq = $row[7];
$glycopeptide[$hits] = $row[1];
/* Manually entering string here also gives undefined values */
/* $mz = " I was not able to include the mz string due to message size limit "; */
$mz = base64_decode($row[4]);
$unc_mz = gzuncompress($mz);
$max = strlen($unc_mz);
$counter = 0;
for ($i = 0; $i < $max; $i = $i+4) {
$temp = substr($unc_mz,$i,4);
$temp = unpack("f",$temp);
$mz_array[$counter] = $temp[1];
$counter++;
}
$hits++;
}
$query = sprintf("select precursor.mzValue, glycoPeptide.protein, binaryDataArray.arrayLength, binaryDataArray.encodedLength, binaryDataArray.arrayData from glycoPeptide, spectrum, binaryDataArray, run, precursor where run.glycoPeptide = glycoPeptide.id AND spectrum.run = run.id AND precursor.run = run.id AND binaryDataArray.spectrum = spectrum.id AND precursor.id = spectrum.precursor AND spectrum.spectrum like 'intensity' AND precursor.mzValue like '%s' and glycoPeptide.protein like '%s' and run.glycoSite like '%s' and run.glycoType like '%s' ORDER by glycoPeptide.protein, spectrum.spectrum",(string)$prec, (string)$gp, (string)$site, (string)$type);
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
/* Manually entering string here also gives undefined values */
/* $int = " Copy the string from above in here "; */
$int = base64_decode($row[4]);
/* The result from this is the above binaryString */
/* echo $row[4]; */
$unc_int = gzuncompress($int);
$max = strlen($unc_int);
$counter = 0;
$max_int = 0;
for ($i = 0; $i < $max; $i = $i + 4) {
$temp= substr($unc_int,$i,4);
$temp = unpack("f",$temp);
$int_array[$counter] = $temp[1];
$counter++;
if ($temp[1] > $max_int) {
$max_int = $temp[1];
$counter++;
}
}
}
/* The following chunk is just to test the arrays */
for ($i = 0; $i < $counter; $i++) {
echo $i;
echo " - ";
echo $mz_array[$i];
echo " - ";
echo $int_array[$i];
echo "<br/>";
}
for ($i = 0; $i < $counter; $i++) {
$plot_data[$i] = array('',$mz_array[$i],$int_array[$i]);
}
// Plot the regular spectrum
$width = 1024;
$height = 768;
$plot = new PHPlot($width,$height);
$plot->SetMarginsPixels(NULL,NULL,NULL,35);
$plot->SetPrintImage(False);
$plot->SetPlotType('thinbarline');
//$plot->SetXTitle('m/z Values');
$plot->SetXTickAnchor('400');
$plot->SetDataColors('red');
$plot->SetXTickIncrement('200');
$plot->SetXDataLabelPos('none');
$plot->SetYTitle('Intensity');
$plot->SetYTickAnchor('0');
//Might need to define this dynamically with nested if/else loops
$plot->SetYTickIncrement('100000');
$plot->SetDataType('data-data');
$plot->SetDataValues($plot_data);
$plot->SetTitle('Fragmentation Spectrum');
//$plot->DrawGraph();
mysql_close($link);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Query result page</title>
<script src="jquery-1.9.1.min.js"></script>
</head>
<script>
var gp = '<?php echo htmlspecialchars($_GET['gp']); ?>';
$(document).ready(function() {
$('.button').click(function() {
window.open('http://www.uniprot.org/uniprot/?query='+gp+'+AND+organism:human&sort=score');
});
$('.XY').click(function() {
var mz_array = <?php echo json_encode($mz_array) ?>;
var int_array = <?php echo json_encode($int_array) ?>;
var table =
"<table border=\"1\">"
+"<tr>"
+"<th>m/z</th>"
+"<th>intensity<t/h>"
+"</tr>";
var max = <?php echo $counter ?>;
for (var i = 0; i < max; i++) {
table += "<tr>"
+"<td>"+mz_array[i]+"</td>"
+"<td>"+int_array[i]+"</td>"
+"</tr>";
}
table += "</table>";
var disp = window.open();
$(disp.document.body).html(table);
});
});
</script>
<body>
<p>The displayed spectrum belongs to <?php echo $gp ?> with a precursor [M+H] of <?php echo (($prec*$charge)-($charge+1)); ?>.<br>
The peptide belonging to this glycopeptide has a mass of <?php echo $pepmass ?> and sequence: <?php echo $pepseq ?>.<br>
<button class="button">Uniprot search</button> <button class="XY">Display XY data</button></p>
<img src="<?php echo $plot->EncodeImage();?>" alt="Plot Image">
</body>
</html>
It's very complicated:
$max = strlen($unc_mz);
$counter = 0;
for ($i = 0; $i < $max; $i = $i+4) {
$temp = substr($unc_mz,$i,4);
$temp = unpack("f",$temp);
$mz_array[$counter] = $temp[1];
$counter++;
}
use this instead:
$mz_array = array_values(unpack("f*", $unc_mz));
I was incrementing one of the indexes where I shouldn't have, the $counter++ inside the if ($temp[1] > $max_int) { // stuff } was bumping the index upon detecting a new maximum value.
The new code for the int_array now looks like this (using Sectus' trick and max(array)):
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$int = base64_decode($row[4]);
$unc_int = gzuncompress($int);
$int_array = array_values(unpack("f*",$unc_int));
$max_int = max($int_array);
}
The following syntax is also valid (if you do not wish to use Sectus' trick):
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$int = base64_decode($row[4]);
$unc_int = gzuncompress($int);
$max = strlen($unc_int);
$counter = 0;
$max_int = 0;
for ($i = 0; $i < $max; $i = $i + 4) {
$temp= substr($unc_int,$i,4);
$temp = unpack("f",$temp);
$int_array[$counter] = $temp[1];
$counter++;
if ($temp[1] > $max_int) {
$max_int = $temp[1];
}
}
}
I would like to thank everyone that cracked their heads over this as well.

Categories