PHP: How to print row of multidimensional array with conditions - php

I'm a PHP beginner. I would like to print rows based on specific condition. For Example, I have a set of Data from SQL-Query(shown below) and I want to print all rows of [Series no] only when Type = 210 and Category = J. I know 'foreach' loop should be used in this case, but I do not know how.
And this is what I've tried. I know it is wrong but as I said I am a beginner and self learning.
$get_data = sqlsrv_query($connde, $mainquery);
$data_array = [];
while ($row = sqlsrv_fetch_array($get_data, SQLSRV_FETCH_ASSOC)) {
$data_array[$row["Type"]][$row["Category"]][$row["Series No"]][$row["End Date"]];
}
foreach ($data_array as $value1) {
if ($value1 = 210) {
foreach ($value1 as $value2) {
if isset($value2 == 'J')
echo "<td>" . $row["Series No"] . "</td>";
}
}
}

You can deal with the rows directly:
<?php
$mainquery = 'SELECT `Type`, `Category`, `Series No`, `End Date` FROM `Foo`';
$get_data = sqlsrv_query($connde, $mainquery);
while ($row = sqlsrv_fetch_array($get_data, SQLSRV_FETCH_ASSOC)) {
if($row['Type'] == 210 && $row['Category'] == 'J') {
echo "<td>" . $row['Series No'] . "</td>";
}
}

Related

join in if loop to join to values

trying to join to 2 xml files with the same value , but when i echo the result it separates the value .
foreach(glob("tarea/*.{assemble.xml,report.xml}", GLOB_BRACE) as $filename) {
$Keys =simplexml_load_file($filename);
foreach($Keys as $Key) {
$key1 = $Keys->ProductKeyID;
$pk = $Keys->ProductKey;
$key2 = $Keys->ProductKeyID;
$serial = $Keys->SerialNumber;
if ($key1 == $key2) {
echo "<tr>";
echo "<td>" .$pk."</td>";
echo "<td>" .$key1."</td>";
echo "<td>" .$key2."</td>";
echo "<td>" . $serial."</td>";
echo "</tr>";
break;
}
}
}
is there any way of putting something like
if key1 = key2 join the together
this is my result im hoping to put all in one line .
ProductKey ProductKeyID ProductKeyID SerialNumber
1234 3305492290985 3305492290985
3305492290985 3305492290985 23

How to sort data on php laravel before exporting them on .csv?

I am trying to sort the datas before exporting them on excel. This is the code that I have been using:
public function getDashboardReport2(){
(...)
echo "<tr><td>Group Name</td><td>Unit</td><td>Unit Number</td><td>First Name</td><td>Last Name</td><td>Phone Number</td></tr>";
($group = \App\Group::find($auth_event->group_id);
$bookings = \App\EventBookings::where("group_id", "=", $auth_event->group_id)->get();
if($bookings->count() > 0){
foreach ($bookings as $booking){
$egroup = \App\EventGroup::find($booking->eg_id); // Here I tried orderBy('name');
$chalet = \App\Chalet::find($booking->chalet_id);
if($egroup) {
$egroup_members = \App\EventGroupMembers::where("eg_id", "=", $egroup->eg_id)->get();
$row = 0;
if ($egroup_members->count() > 0) {
foreach ($egroup_members as $egroup_member) {
$row++;
$user = \App\User::find($egroup_member->user_id);
if ($user) {
$charges = \App\EventBookingCharges::where("user_id", "=", $user->user_id)
->where("booking_id", "=", $booking->booking_id)->get();
$paid_amount = 0;
$balance_amount = 0;
if ($charges->count() > 0) {
foreach ($charges as $charge) {
if ($charge->status == 1) {
$paid_amount = $paid_amount + $charge->amount;
} else {
$balance_amount = $balance_amount + $charge->amount;
}
}
})
echo "<tr>";
if ($row == 1) {
echo "<td>" . $egroup->name . "</td>"; // Sort using this data
} else {
echo "<td></td>";
}
if ($row == 1) {
echo "<td>" . ($chalet ? $chalet->name : '') . "</td>";
} else {
echo "<td></td>";
}
echo "</tr>";
}
}
echo "<tr><td colspan='9'><br></td></tr>";
}
}
}
}
echo "</table>";
}
}
How do I sort this one out? I have tried orderBy('name'); but it didn't work. I also tried searching it on google but all the tutorials are about sorting arrays.
ok i think i understand now what you want to order. you want to order the bookings according to their egroups name!
Im afraid I dont see an immediate answer for that unless you saved not only the eg_id in the bookings table but also the eg_name. then you could do something like
$bookings = \App\EventBookings::where("group_id", "=", $auth_event->group_id)->orderBy('eg_name')->get();
sorry for not being able to provide a better answer but i hope i could still be of help

Add links to data in HTML table Created using PHP and a MYSQL database

I am trying to pull data from a table in PHPmyadmin and convert it to an HTML table based on some customer form input which filters out unneeded rows. The code below does that fine. The issue is that two of my columns need to contain links.
It would be easy enough to use PHP to change the table data into the link using a strtolower() and str_replace() to remove spaces, then concatinating the "www.website.com/" and the ".html". But I'm using a foreach loop to get all of the rows that I need and I don't know how to only alter one value per row.
I have tried using "Broswer Display Transformations" and "Input Transformations" in PHPmyadmin, but that only seems to affect the data in PHPmyadmin and not when I access the data via PHP.
My current code:
//* Code for Table
$query = "SELECT $searchFields FROM `hose_reels` $searchPhrase ORDER BY `model` ASC";
$result = mysqli_query($cxn,$query);
if ($row[$key] != "0") {
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
echo "<th>" . $key . "</th>";
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
echo "<td>$row[$key]</td>";
}
echo "</tr>";
}
echo "</table>";
}
else {
echo "<p>No results match your selection. Please broaden your search.</p>";
}
Just add <a> tag in your php code. Below is the code. One more thing you have error in echo "<td>$row[$key]</td>"; line . it prints <td>$row[$key]</td> not the result you are fetching from DB.
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
$i = 1;
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
if($i == 1 || $i ==3){
echo "<th><a href='".key ."'" . $key . "</a></th>";
}else{
echo "<th>" . $key . "</th>";
}
$i++;
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
$j =1;
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
if($i == 1 || $i ==3){
echo "<td><a href='".$row[$key]."'".$row[$key]."</a></td>";
}else{
echo "<td>$row[$key]</td>";
}
}
echo "</tr>";
}
echo "</table>";

Number_format specific item in foreach php

Thanks for directing the link about the mySql API, i think there is a need to change to mySQLi or PDO. I have post the near-complete code below of same case, as my first time, could you please help what's error below, as it doesn't show the results as expected as the code using mysql_... please help. (assuming the select statement is correct please.)
<?php
$Ticker = htmlspecialchars($_GET["Ticker"]);
$StartDate = htmlspecialchars($_GET["StartDate"]);
$EndDate = htmlspecialchars($_GET["EndDate"]);
echo "<td>testing.</td>";
echo "</table>";
$pdo = new PDO('mysql:host=;dbname=, ,);
$statement = $pdo->query("Select Ticker, xxx as 'Last Update',Price, xxx as TTlUndetAmt,
FROM trade
WHERE Ticker = '$Ticker' and DATE(xxx) between '$StartDate' and '$EndDate'
GROUP BY Ticker, date
ORDER BY Ticker ASC, Date(ReleaseDT) DESC");
$row = $statement->fetch(PDO::FETCH_ASSOC);
//echo htmlentities($row['_message']);
echo "<table>";
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
if ($value === end($row)) {
echo number_format($value);
} else
{
echo $value . ",";
}
}
echo " </td></tr> " . "\n";
$i++;
}
?>
I got the results from select statement from mysql database. I use php to get the required data. I want specify the format only a specific item of each row to be numeric, i.e. (thousand separated). How could I do so? can below code do so?
Current output:
ticker1,2014-09-03 ,1.190,0,37247000
ticker2,2014-09-03 ,1.180,0,23246000
ticker3,2014-09-03 ,1.170,0,19188000
Expected Output:
ticker1,2014-09-03 ,1.190,0,37,247,000
ticker2,2014-09-03 ,1.180,0,23,246,000
ticker3,2014-09-03 ,1.170,0,19,188,000
The code I am using:
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
echo $value . ",";
if ($value === $row[5]) {
echo number_format($value);
}
}
echo " </td></tr> " . "\n";
$i++;
}
echo "</table>";
I found out that the above code will create duplicate role at the last row [5].
To my limited knowledge, I changed to
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
if ($value === end($row)) {
echo number_format($value);
} else
{
echo $value . ",";
}
}
echo " </td></tr> " . "\n";
$i++;
}
I would incorporate the key. That way, you can just check for the field name:
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $key => $value) {
echo $value . ",";
if ($key === 'YourFieldName') {
echo number_format($value);
}
}
echo " </td></tr> " . "\n";
$i++;
}
echo "</table>";
The function mysql_fetch_assoc already returns a key/value array, so you don't need anything there. Note though, that mysql_fetch_assoc is part of an old and deprecated API. If you like, have a look at: Choosing a MySQL API.
I would bring in the names, and use a $key=>$val in your foreach as such:
foreach ($row as $key=>$value)
{
echo $value . ",";
if ($key == "theRightColumn") // guessing the column name
{
echo number_format($val);
}
else
{
echo $val;
}
}
You have to change the modification in this line
foreach ($row as $value) {
to
foreach ($row AS $key => $value) {

Building a Table of Data with an Array of Arrays

I have an Array of Arrays and Want to create a Tabular data layout. This is not the exact code, as how their generated is quite the cluster (Coming from COBOL interaction) but this should give me enough to make it work if someone can think of a clean way to code this.
array(
Array(847.0, 97010, 11)
Array(847.0, 97012, 10)
Array(847.1, 97010, 08)
Array(847.1, 97012, 14)
)
So I want to put these into a Table that looks something like
97010 97012
847.0 11 10
847.1 08 14
The first 2 elements of the arrays will always be the two axis and the 3rd the contents of the table.
Any Suggestions? thanks!
$table = array();
$columns = array();
// copy the array (x, y, value) into a table
// keeping track of the unique column names as we go
foreach ($dataSet as $point) {
// provided sample data used floats, ensure it is a string
$x = strval($point[0]);
$y = strval($point[1]);
$data = $point[2];
if (!isset($table[$x])) {
$table[$x] = array();
}
$table[$x][$y] = $data;
// quick and dirty style 'unique on insert'
$columns[$y] = true;
}
// switch the column names from title => true to just titles
$columns = array_flip($columns);
// Display the table
echo '<table>';
// Header row
echo '<tr>';
echo '<th> </th>';
foreach ($columns as $columnTitle) {
echo '<th>' . $columnTitle . '</th>';
}
echo '</tr>';
// Bulk of the table
foreach ($table as $rowTitle => $row) {
echo '<tr>';
echo '<th>' . $rowTitle . '</th>';
foreach ($columns as $columnTitle => $junk) {
if (isset($row[$columnTitle]) {
echo '<td>' . $row[$columnTitle] . '</td>';
} else {
// Handle sparse tables gracefully.
echo '<td> </td>';
}
}
echo '</tr>';
}
echo '</table>';
From what I understood:
$arr[847.0][97010] = '11';
$arr[847.0][97012] = '10';
$arr[847.1][97010] = '08';
$arr[847.1][97012] = '14';
And you may create a table:
$result = "<table>";
foreach($arr as $row_key => $row) {
$result .= "<tr>";
foreach($row as $column_key => $data) {
$result .= "<td>".$data."</td>";
}
$result .= "</tr>";
}
$result .= "</table>";
echo $result;

Categories