I need to fill a multidimensional array and here is my code I have so far for it.
while($num > $i)
{
$default[$i]=0;
$defaultcounter=0;
$default2[$i]=0;
$default3[$i]=0;
$query="Select * from `issues` WHERE `app`='" . $applist[$i] . "'" . "AND `startmonth`='". $month ."' ORDER BY `id` ASC";
$result=mysql_query($query);
while($row = mysql_fetch_array($result))
{
$downtime[$i]+=$row['duration'];
$default2[$i]++; //Number of Incidents Variable
$defaultcouinter++;
$times[$i] = array();
$times[$i][$defaultcounter[$i]]=$row['startday'].$row['starttime'];
}
$appavail[$i]=100 -(ceil($downtime[$i] * 100 / $totaltime));
$default[$i] = (ceil($downtime[$i] / $defaultcounter));
$i++;
}
Apparently I am not doing the array assignment correct. I need to to have my number of rows counted with the $i variable outside of my while then inside the while the defaultcounter will be keeping up with the column. I tried just doing a $time[$i][defaultcounter] and it didn't like it. Whats the proper syntax for assigning a multidimensional array?
Thanks
$times[$i] = array() should be out (before) the while loop unless you want it redefining $times as an empty array in each iteration (reseting values). Apart from that, you're assigning the values correct, although it looks a bit odd (not sure what you want to achieve there). This are the general formulas, should give you an idea:
$array[] = $subarray;
$array[$subarray] = $value;
$array[$subarray][] = $value;
$array[$subarray][$i] = $value;
Related
<?php
$q = "SELECT `Code` FROM `productspecs` GROUP BY `Code` HAVING COUNT(1) > 1";
$r = mysqli_query($conn, $q);
$a = 0;
while ($row = mysqli_fetch_array($r))
{
echo $row['Code'];
$q2 = "SELECT * FROM `productspecs` WHERE `Code`='" . $row['Code'] . "'";
$r2 = mysqli_query($conn, $q2);
$i = 0;
while ($row2 = mysqli_fetch_array($r2))
{
$Mod = $row2['ModificationDate'];
$ModDates[] = DateTime::createFromFormat('d/m/Y', $Mod); // === $ModDates[$i]
$ModDates[$i]['SpecID']=$row2['SpecID'];
$i++;
}
usort($ModDates); // <<< ??
$DeleteIDs[] = $ModDates[0]['SpecID'];
foreach ($ModDates as $ModDate)
{
echo $ModDate->format('d-m-Y');}
unset($ModDates); // unset the array for the next code
echo '</br>';
echo 'Delete: ' . $DeleteIDs[$a];
$a++;
}
?>
Hi I'm trying to Delete specifications from the product database (or at least get a list of ones to delete) where we have duplicates and we want to delete the oldest one.
So here I've 1) found a list of duplicate codes 2) Assigned spec id to each mod date 3) Sorted the mod dates to find the oldest*NOTE 4) Found a list of ids to delete by finding the id assigned to the first of the sorted array. 5) unsets the moddate array for the next set of duplicates
NOTE: I think solving this problem might have something to do with sorting the multidimensional array - this is the part that I'm fairly sure is wrong. If this wasn't a multidimensional array we would at least see the modification dates in order. At this point I COULD just do a search for product code and oldest (first in array) mod date which thinking about it now - would achieve the same result? Does it matter that the primary key will be lost - after all - all I need is to get rid of the product code with the older modification date.. it doesn't matter that we don't have the primary key?
P.S. I did see a post about sorting multi-dimensional arrays Here but I felt I should show you what I was doing in case somebody had a better suggestion?
<?php
$q = "SELECT `Code` FROM `productspecs` GROUP BY `Code` HAVING COUNT(1) > 1";
$r = mysqli_query($conn, $q);
$a = 0;
That $a variable seems useless.
while ($row = mysqli_fetch_array($r)) {
echo $row['Code'];
$q2 = "SELECT * FROM `productspecs` WHERE `Code`='" . $row['Code'] . "'";
$r2 = mysqli_query($conn, $q2);
$i = 0;
while ($row2 = mysqli_fetch_array($r2)) {
$Mod = $row2['ModificationDate'];
$ModDates[] = DateTime::createFromFormat('d/m/Y', $Mod); // === $ModDates[$i]
$ModDates[$i]['SpecID'] = $row2['SpecID'];
$i++;
If $ModDates[] === $ModDates[$i], as you say, then write $ModDates[$i] in both assignments. $ModDates[] === $ModDates[$i]can be wrong, $ModDates[$i] === $ModDates[$i] cannot.
Moreover :
$ModDates[] = ...
$ModDates[$i]['SpecID'] = $row2['SpecID'];
Now, whatever has been assigned to $ModDates[$i] in the first line is gone, it's now an array with only one key : 'SpecId'.
}
usort($ModDates); // <<< ??
What does that comment mean ?
$DeleteIDs[] = $ModDates[0]['SpecID'];
You put only one value from the array into $DeleteIDs. Why ?
foreach ($ModDates as $ModDate) {
echo $ModDate->format('d-m-Y');}
unset($ModDates); // unset the array for the next code
That foreach will iterate only once because the line right above unsets the array it's iterating over.
In case it's a mistake and you in fact wanted to unset $ModDate :
- That will teach you to use variables with names you can differenciate
- That wouldn't want anyway because $ModDate is a copy of an entry of $ModDates, not that entry itself. Unseting it changes nothing in $ModDates.
echo '</br>';
echo 'Delete: ' . $DeleteIDs[$a];
$a++;
}
}
I added the two last curly brackets, I don't know if you pasted wrongly or if you simply forgot to put them in your code.
I have been trying to loop this query but all I get is the first value.
When I do the same command in workbench I get all the values.
What am I doing wrong here? Any answers are much appreciated!
global $db;
$stmt12 = $db->query('SELECT `Value` FROM overriddenpropertyvalues WHERE ParentGUID LIKE "' . $itemguid . '";');
$propertyvaluerow = $stmt12->fetch();
while ($propertyvaluerow != null) {
You are fetching only one value with ->fetch(). That's why you receive only one value.
Example from here:
$query = $db->prepare('SELECT `Value` FROM `overriddenpropertyvalues` WHERE ParentGUID LIKE :like');
$query->execute([':like' => $itemguid]);
$stmt->bind_result($value);
while ($query->fetch()) {
echo $value."<br/>"
}
There might possibly be a loophole in your Program depending on what the $stmt12->fetch() does. If it fetches an Array of Data, your while loop might not behave as expected. Below is a commented alternative to what you might want to try out:
<?php
global $db;
$stmt12 = $db->query('SELECT `Value` FROM overriddenpropertyvalues WHERE ParentGUID LIKE "' . $itemguid . '";');
// ASSUMES YOU ARE USING PDO SO WE FETCH ALL THE DATA
$propertyvaluerow = $stmt12->fetchAll();
// THERE MIGHT BE A LOOPHOLE IN YOUR PROGRAM DEPENDING ON WHAT $stmt12->fetch() IS AND DOES
// ASSUMING IT FETCHES AN ARRAY OF NESTED OBJECTS OR SCALAR VALUES, THE WHILE LOOP WOULD NOT BEHAVE AS EXPECTED.
// THAT MEANS IF IT IS AN ARRAY YOU COULD USE A DIFFERENT CONSTRUCT LIKE THE ONE BELOW YOUR WHILE CONSTRUCT:
/* while ($propertyvaluerow != null) { */
// CREATE A $count VARIABLE TO HOLD THE INCREMENTAL COUNT THROUGH THE ITERATION:
$count = count($propertyvaluerow);
while($count > 0){
// DO YOUR WORK HERE
//DECREMENT THE VALUE OF COUNT OTHERWISE YOU MAY HAVE AN INFINITE LOOP TO DEAL WITH.
$count--;
}
?>
There is yet another alternative:
<?php
// OR EVEN A MUCH MORE EASIER WAY IS TO USE THE FOREACH LOOP, WHICH ACHIEVES THE SAME THING AS THE WHILE LOOP:
foreach($propertyvaluerow as $iKey=>$objData){
// SIMPLY USE THE $objData IN WITHING THE LOOP
// THE $objData IS THE VALUE OF THE CURRENT OBJECT IN THE $propertyvaluerow IN THE ITERATION
}
Best way:
global $db;
$stmt = $db->prepare('SELECT `Value` FROM OverriddenPropertyValues WHERE ParentGUID=?');
$stmt->execute([$itemguid]);
$rows = $stmt->fetchAll();
foreach($rows as $row) {
// $row->Value or $row['Value']
}
What would be a direct way to turn comma separated data from a mysql table, into a simple php array, other than doing it like I'm doing now?
I current do this in a very messy way by selecting data, then concatenating it into a string, which I later use.
I'm using PDO here.
Data is simple
locations
-------------------
US,UK,SE,DE
DE,SE,CA
GB,US,DE,SE
AU,NZ,GB
pdo
$d = $db->prepare('select locations a from destinations');
$d->execute();
$d->bindColumn('a',$a);
$count = $d->rowCount();
if($count >= 1) {
$b = '';
while($row = $d->fetch()) {
$b .= $a.',';
}
} else {
$b = 'No records to display';
}
echo $b;
The output I'm hoping to achieve is just a simple array like below, which is all the rows joined together.
Desired output
array('US','UK','SE','DE','DE','SE','CA','GB','US','DE','SE','AU','NZ','GB')
Can you help?
You're almost there. The easiest thing you can do is use explode(',', $b) for the complete string you have now, and frankly, I'm a bit surprised that you couldn't figure that part out after writing all that code.
Instead of concating everying in PHP, you can also concat it in the query using the GROUP_CONCAT function. This will introduce a limit, though, since the result of GROUP_CONCAT can be at most 32k, if I remember correctly.
Below is an alternative approach. Here, each row is fetched and exploded to an array immediately. That array is merged with (appended to, actually) to one big resulting array.
The advantage is that you are not concatting a big string first, which is relatively inefficient, but in practice, I doubt if you can tell the difference in performance.
$d = $db->prepare('select locations a from destinations');
$d->execute();
// An array for results.
$results = array();
$d->bindColumn('a',$a);
$count = $d->rowCount();
if($count >= 1) {
$b = '';
while($row = $d->fetch()) {
// explode each row and append it to the array.
$results = array_merge($results, explode(',', $a));
}
} else {
$b = 'No records to display';
}
// Display the complete array.
print_r($results);
You could just select the entries and then turn them into arrays by "exploding" them like this:
$locationArray = explode(",", $databaseEntry);
This will seperate your database entries by comma and add each entry to the array.
Documentation: http://php.net/manual/de/function.explode.php
Hope I could help
I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>
What I want to do here is to be able to assign the values from sql query into arrays.
And then compute for the total.
<?php
include('conn.php');
$qreports=query_database("SELECT S_PRICE, PID, QTY_PUR, ITEM_ID, CUSID, CNUM, Cust_Name, TDATE FROM prod_table, customer_credit, sales_trans_items WHERE prod_table.PID=sales_trans_items.ITEM_ID AND sales_trans_items.CNUM=customer_credit.CUSID AND sales_trans_items.TDATE='2011-02-06 09:14:09'","onstor",$link);
$grandtotal=0;
$customer="";
while($qrep=mysql_fetch_assoc($qreports)){
$pid=$qrep['PID'];
foreach ($pid as $k => $v) {
$sids=$v;
$qtypur=$qrep['QTY_PUR'][$k];
$sprice=$qrep['S_PRICE'][$k];
$customer=$qrep['Cust_Name'][$k];
$tdate=$qrep['TDATE'][$k];
$stot=$qtypur * $sprice;
$grandtotal =$grandtotal + $stot;
}
}
echo "Customer: ". $customer."<br/>";
echo "Profit: ". $grandtotal;
?>
I tried the query on phpmyadmin before I place it in the code, and it output this:
I think you misunderstood how mysql_fetch_assoc works: Every call returns one row from the result set. $grep is an array with structure columnname => value.
That also means that $qrep['PID'] cannot be an array and your foreach loop won't work. In every loop, $qrep['PID'] contains one of the values you see in the PID column in your screen shot.
I suggest you add print_r($qreq); in your while loop so you get more familiar with the structure of the array.
As each $qrep is an array itself, creating a result array is just adding each of these to a new array:
$result = array();
while(($qrep=mysql_fetch_assoc($qreports))) {
$result[] = $qrep;
}
Now you are performing some more computation where I am not sure what you want to get in the end but it seems you are multiplying each QTY_P with S_PRICE:
$total = 0;
foreach($result as $report) {
$total += $report['QTY_P'] * $report['S_PRICE'];
}
(You could however also compute this in your while loop)
Assuming you want to get the overall sum and the sum for each customer:
$total = 0;
$total_per_customer = array();
foreach($result as $report) {
$customer = $report['Cust_Name'];
if(!array_key_exists($customer, $total_per_customer)) {
$total_per_customer[$customer] = 0;
}
$price = $report['QTY_P'] * $report['S_PRICE'];
$total_per_customer[$customer] += $price;
$total += $price;
}
In the end, $total_per_customer is an array with customer names as keys and the sum of the prices as values. $total will contain the sum of all prices.
You question is a bit unclear, but i think the answer wont be far a way from the following suggested references:
As you loop through the rows use
something like $array[] =
$qrep['columnName'] to populate an
array.
Then, check out PHP's array_sum().