Is there a way I can sort this array - php

I want to sort a returned value from a while loop here is my code
public function Getter($stream){
$sql1 = "SELECT reg_no FROM hs_registration ";
$sql1.= "JOIN hs_students USING(reg_no) WHERE class_id = 2";
$result1 = $database->query($sql1);
$num1 = $database->num_rows($result1);
if($num1 > 0){
$records = array();
$number_of_sub = getNoSub();
while($row = mysqli_fetch_array($result1)){
//return individual score
$total = $this->totalScoreSpreadSheet($row['reg_no'], $stream);
$flyAvg = $total / $number_of_sub;
$records[] = number_format($flyAvg,2).' '.$row['reg_no'];
}
}
return $records;
}
$averages = Getter($stream);
foreach ($averages as $avg){
echo $avg
}
Please, I want to sort the output based on the avg with the students reg_no appended to it
Output
54.20 FMS34
91.00 FMS51
72.16 FMS64
44.81 FMS23
68.52 FMS30
48.65 FMS37
My desired output is
Output
91.00 FMS51
72.16 FMS64
68.52 FMS30
54.20 FMS34
48.65 FMS37
44.81 FMS23

If your leading numbers are always two digits, then a decimal point, the two digits, then rsort($records); would suffice.
If they might be anything else, then keep a separate sorting array, then use array_multisort() to modify the $records.
public function Getter($stream): array
{
$sql = "SELECT reg_no
FROM hs_registration
JOIN hs_students USING(reg_no)
WHERE class_id = 2";
$flyAvgs = [];
$records = [];
$number_of_sub = getNoSub();
foreach ($database->query($sql) as $row) {
$total = $this->totalScoreSpreadSheet($row['reg_no'], $stream);
$flyAvg = $total / $number_of_sub;
$flyAvgs[] = $flyAvg;
$records[] = number_format($flyAvg, 2) . ' ' . $row['reg_no'];
}
array_multisort($flyAvgs, SORT_DESC, $records);
return $records;
}

Related

PHP sql statement where clause to multiple array values

How do i use where clause for array if value[3] has multiple data stored
$fsql="select * from Error where RptDatime = 201706091000 and partnumber like ('$value[3]')";
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo 'ID:'.$id.'Machine Number :'.$mac;
}
You can use regex function instead of like. Below is the sample code for you.
$partnumner = [];
foreach($value[3] as $v)
{
$partnumber[] = "*.".$v.".*";
}
$fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP '".implode("|",$partnumber)."'";
If you still wish to use like, you can follow the answer here
I assume that you have array of numbers so, first you should validate for expected data and then to implode it into comma separated string.
if(!isset($value[3])){
return false;
}
if(!is_array($value[3])){
return false;
}
foreach($value[3] as $number){
if(!is_numeric($number)){
return false;
}
}
$numbers = implode(",",$value[3]);
$fsql=sprintf("select * from Error where RptDatime = 201706091000 and partnumber in (%s)",$numbers);
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo 'ID:'.$id.'Machine Number :'.$mac;
}

Translating a database to JSON

I have a method of creating JSON into an array that looks like this:
[{"date":"","name":"","image":"","genre":"","info":"","videocode":""},{...},{...}]
I first tried getting the data from a html page (not the database) like this:
$arr = array();
$info = linkExtractor($html);
$dates = linkExtractor2($html);
$names = linkExtractor3($html);
$images = linkExtractor4($html);
$genres = linkExtractor5($html);
$videocode = linkExtractor6($html);
for ($i=0; $i<count($images); $i++) {
$arr[] = array("date" => $dates[$i], "name" => $names[$i], "image" => $images[$i], "genre" => $genres[$i], "info" => $info[$i], "videocode" => $videocode[$i]);
}
echo json_encode($arr);
Where each linkExtractor looks a bit like this - where it grabs all the text within a class videocode.
function linkExtractor6($html){
$doc = new DOMDocument();
$last = libxml_use_internal_errors(TRUE);
$doc->loadHTML($html);
libxml_use_internal_errors($last);
$xp = new DOMXPath($doc);
$result = array();
foreach ($xp->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' videocode ')]") as $node)
$result[] = trim($node->textContent); // Just push the result here, don't assign it to a key (as that's why you're overwriting)
// Now return the array, rather than extracting keys from it
return $result;
}
I now want to do this instead with a database.
So I have tried to replace each linkExtractor with this - and obviously the connection:
function linkExtractor6($html){
$genre = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
foreach ($genre as $node)
$result[] = $node;
return $result;
}
But I am getting the error:
Invalid argument supplied for foreach()
Avoid redundancy and run a single SELECT
function create_json_db($con){
$result = mysqli_query($con,"SELECT date, name, image, genre, info, videocode
FROM entries
ORDER BY date DESC");
$items= array();
while ($row = mysqli_fetch_assoc($result)) {
$items[] = $row;
}
return $items ;
}
Try to use this. More info in the official PHP documentation:
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$items = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$items[] = $row;
}
return $items;
}
First, you are not iterating through your results via something like mysqli_fetch_array. So here is the function with mysqli_fetch_array in place. But there is a much larger issue. Read on.
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Okay, with that done, it still won’t work. Why? Look at your function. Specifically this line:
$result = mysqli_query($con,"SELECT genre
But where is $con coming from? Without a database connection mysqli_query will not work at all. So if you somehow have $con set outside your function, you need to pass it into your function like this:
function linkExtractor6($con, $html){
So your full function would be:
function linkExtractor6($con, $html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Remember, functions are self-contained & isolated from whatever happens outside of them unless you explicitly pass data into them.

MYSQL printing a database record array

function CHECKPENDINGORDERS($con, $oc, $pos){
if(is_resource($con)){
$sql = "SELECT * FROM eats_orders WHERE school_code = '$oc' AND order_status = '$pos'";
$sqlresult = mysql_query($sql);
#$pendingorderrow = mysql_fetch_array($sqlresult);
while($row = mysql_fetch_assoc($sqlresult)){
$a[] = $row;
return $a;
}
}
}
$checkpendingorders = CHECKPENDINGORDERS(MYSQL_LINK, $ordercode, $pendingorderstatus);
print_r($checkpendingorders);
I have the function above me to retrieve db records to and print it out by calling the function. But it is only printing 1 recording but I have multiple records with same ordercode and pendingorderstatus.
You need to return your $a at the end
<?php
function CHECKPENDINGORDERS($con, $oc, $pos){
if(is_resource($con)){
$sql = "SELECT * FROM eats_orders WHERE school_code = '$oc' AND order_status = '$pos'";
$sqlresult = mysql_query($sql);
#$pendingorderrow = mysql_fetch_array($sqlresult);
while($row = mysql_fetch_assoc($sqlresult)){
$a[] = $row;
//return $a; //<---- Not here
}
}
return $a; //<----- Here
}
That is because... You are getting a single row is since you are returning the $a in the first iteration itself.
You need to move your return statement outside of your loop. Once that return statement is reached your function call ends thus terminating your loop.
while($row = mysql_fetch_assoc($sqlresult)){
$a[] = $row;
}
return $a;
To further improve upon your function, your function will throw a E_NOTICE error because you are not defining $a before using it. To solve this just define $a to be an empty string at the top of your function. You can also move the return statement to the end of the array so your function always returns an array, even if it is empty.
function CHECKPENDINGORDERS($con, $oc, $pos){
$a = array();
if(is_resource($con)){
$sql = "SELECT * FROM eats_orders WHERE school_code = '$oc' AND order_status = '$pos'";
$sqlresult = mysql_query($sql);
#$pendingorderrow = mysql_fetch_array($sqlresult);
while($row = mysql_fetch_assoc($sqlresult)){
$a[] = $row;
}
}
return $a;
}

php for each in while loop

I am trying to get specific data from a while loop and loop it x number of times.
I'm selecting this data:
$r=mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0 FROM advertisements WHERE token = '".$_GET['token']."'");
while ($adData = mysql_fetch_array($r, MYSQL_NUM))
{
$data = $adData;
$ac0 = $data['ac0'];
$ac1 = $data['ac0'];
print $ac0;
print $ac1;
}
This doesn't work. Nothing gets printed out.
What I want to do is to get ac6 to ac0 value for that specific advertisement (where token).
How can I do that?
Change your numeric fetch to an associative one, then add a foreach loop to process the result.
$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0
FROM advertisements WHERE token = '" . $_GET['token'] . "'");
while ($adData = mysql_fetch_assoc($r))
{
foreach ($adData as $key => $value)
{
$nubmer = (int)substr($key, 2);
print $value; // or whatever you actually want to do
}
}
Also I hope you're validating $_GET['token'] against possible mischief in your code.
You can create an arrays to add the values from the result query
1st is to create an array:
$advert_AC0 = array();
$advert_AC1 = array();
$advert_AC2 = array();
$advert_AC3 = array();
$advert_AC4 = array();
$advert_AC5 = array();
$advert_AC6 = array();
Now, to add content to array
$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0
FROM advertisements WHERE token = '" . $_GET['token'] . "'");
if(mysql_num_rows($r)){ //check 1st if there is num of rows from the result
while ($adData = mysql_fetch_assoc($r))
{
array_push($advert_AC0, $dData['ac0']);
array_push($advert_AC1, $dData['ac1']);
array_push($advert_AC2, $dData['ac2']);
array_push($advert_AC3, $dData['ac3']);
array_push($advert_AC4, $dData['ac4']);
array_push($advert_AC5, $dData['ac5']);
array_push($advert_AC6, $dData['ac6']);
}
}else{
echo "NO RESULT.";
}
to call for the array values, 1 by 1
$count_array = count($advert_AC0);
$i = $count_array;
while(1 <= $i){
echo "AC0: $advert_AC0[$i]<br>";
echo "AC1: $advert_AC1[$i]<br>";
echo "AC2: $advert_AC2[$i]<br>";
echo "AC3: $advert_AC3[$i]<br>";
echo "AC4: $advert_AC4[$i]<br>";
echo "AC5: $advert_AC5[$i]<br>";
echo "AC6: $advert_AC6[$i]<br>";
$i++;
}
I don't know if my answer solved your question, please comment if not.

Searching Array in PHP and return results

Can't find quite the right answer so hope someone can help. Basically want to create an array and then return the results from a search e.g.
$tsql = "SELECT date, staffid, ID,status, eventid, auditid from maincalendar";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $tsql , $params, $options);
$calarray=array();
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
I would then like to search for values matching 'caldate' and 'staffid' and return the associated entry in $calarray
I suggest the following,
Fetch all data needed for the current month you are showing, using col BETWEEN x AND y
Add them to a array in PHP, with staffid and caldate as key
Something like so;
$calarray[$row['staffid'] . '-' . $row['date']][] = $row;
Not sure if a single staffid/date combination can have one or more events per day, if not you can remove the []
To check if we have information for a specific staffid/date combination, use isset
if (isset($calarray[$staffid . '-' . $mydate]) { ... }
Add indexes to the fields you're going to query, and then move the search to the sql query. You can also make simple filtering inside the loop. So you'll be populating several arrays instead of one, based on the search you need.
try this:
$matches = array();
$caldate = //your desired date;
$staffid = //your desired id;
foreach($calarray as $k => $v){
if(in_array($caldate, $v['caldate']) && in_array($staffid, $v['staffid'])){
$matches[] = $calarray[$k];
}
}
$matches should be and array with all the results you wanted.
also:
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
can be shortened into:
while($row = sqlsrv_fetch_array($stmt)) {
$calarray[] = $row;
}
Maybe this code snipplet solves your problem.
I am not a PHP programmer, so no warrenty.
function searchInArray($array, $keyword) {
for($i=0;$i<array.length();$i++) {
if(stristr($array[$i], $keyword) === FALSE) {
return "Found ".$keyword." in array[".$i."]";
}
}
}

Categories