How to get keys in a PHP array with null values? - php

When I print an array with a string as $key and an array as $value using foreach ($array key => value), the keys with null values are not displayed. Can someone please help me with this?
$stockist = array();
while($row = mysql_fetch_array($result)) {
$pharmacy = trim($row['pharmacy']);
if (isset($stockist[$pharmacy])) {
$medicine = $stockist[$pharmacy];
$medicine[] = trim($row['pharmacy']);
$stockist[$pharmacy] = $medicine;
}
else {
$medicine = array();
$medicine[] = trim($row['medicine']);
$stockist[$pharmacy] = $medicine;
}
}
ksort($stockist);
foreach ($stockist as $key => $value) {
echo "<table align='center' border='1'>";
echo "<tr><td align = 'justify'> <font color = 'blue'> $key</td></tr>";
foreach ($value as $key1 => $value1) {
echo "<tr><td align ='justify'>$value1</td></tr><br>";
}
echo "</table>";
}

This isn't exactly what you're looking for, but it is what the title is asking for ("How to get keys in a PHP array with null values?"--my own question that brought me to this page):
function find_nulls($a) {
return array_keys(array_filter($a, function($b) {
return is_null($b);
}) );
}

You can use for loop instead of foreach.
$stockCount = count($stockist);
for ($stockCount; $i <=0; $i++) {
echo "<table align='center' border='1'>";
echo "<tr><td align = 'justify'> <font color = 'blue'> $stockCount[$i]</td></tr>";
echo "</table>";
}
Hope it will work.

Related

Transpose rows and columns in a 2D array [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 4 years ago.
I have created a table that displays a series of numbers in a table. I am trying to transpose the matrix (flip rows and columns) using a for each loop and a function named transpose_matrix but it doesnt seem to be working for me. Where am I going wrong with this? I am working with the following code:
//Creating rows and columns for text file
echo "<h1>Data Table</h1>";
echo "<table border = 0 >";
foreach($result as $key=>$value){
echo "<tr>";
foreach($value as $v){
echo "<td>".$v."</td>";
}
echo "</tr>";
}
echo "</table>";
}
function transpose_matrix($result) {
$transpose = array(); //
foreach ($result as $key => $sub) {
foreach ($sub as $subkey => $subvalue) {
$transpose[$subkey][$key] = $subvalue;
}
}
return $transpose;
}
My first table displays as expected and looks somthing like this:
1 2 3 4 5
6 7 8 9 10
I need it to appear as such (i.e rotating the position of the rows and columns):
1 6
2 7
3 8
4 9
5 10
I have searched StackOverflow for similar questions or solutions but cannot seem to find one that works. I am fairly new to PHP also so apologies if it is a simple fix
This should give you what you need.
function transpose($array_one) {
$array_two = [];
foreach ($array_one as $key => $item) {
foreach ($item as $subkey => $subitem) {
$array_two[$subkey][$key] = $subitem;
}
}
return $array_two;
}
Then just pipe your existing array into the function and render the resulting array.
Check this: https://3v4l.org/OnuSu
$table = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
];
$i = 0;
$transpose = [];
while ($columns = array_column($table, $i++))
{
$transpose[] = $columns;
}
$table = '<table border="1">';
$rows = count($transpose);
for ($i = 0; $i < $rows; $i++){
$cols = count($transpose[$i]);
$table .= '<tr>';
for ($j = 0; $j < $cols; $j++)
{
$table .= '<td>' . $transpose[$i][$j] . '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
echo $table;
You can just extract the columns of the sub-arrays one-by-one:
foreach(reset($result) as $key => $values) {
$transpose[] = array_column($result, $key);
}
However this is probably better and should work even if the keys are different in each array:
$transpose = array_map(null, ...$result);
Your function seems to be working fine you just need to call it.
Add this below the function:
//Creating rows and columns for text file
$result[0] = ['1','2','3','4','5'];
$result[1] = ['6','7','8','9','10'];
$result[2] = ['11','12','13','14','15'];
$result[3] = ['16','17','18','19','20'];
$result[4] = ['21','22','23','24','25'];
echo "<h1>Data Table</h1>";
echo "<table border = 0 >";
foreach($result as $key=>$value){
echo "<tr>";
foreach($value as $v){
echo "<td>".$v."</td>";
}
echo "</tr>";
}
echo "</table>";
function transpose_matrix($result) {
$transpose = array(); //
foreach ($result as $key => $sub) {
foreach ($sub as $subkey => $subvalue) {
$transpose[$subkey][$key] = $subvalue;
}
}
return $transpose;
}
$mat = transpose_matrix($result);
echo "<h1>Data Table</h1>";
echo "<table border = 0 >";
foreach($mat as $key=>$value){
echo "<tr>";
foreach($value as $v){
echo "<td>".$v."</td>";
}
echo "</tr>";
}
echo "</table>";

apply css to specific element in array

I am fetching data of employees from mysql database into array and displaying in table.
everything is working but i want to apply a condition in array that
If salary is greater then 30,000 then change its color to red .
Tried
$q = "select name, salary from array";
$res = mysqli_query($link, $q);
$arr = array();
while ($data = mysqli_fetch_assoc($res)) {
$arr[] = $data;
}
echo '<table class="table table-hover">
<th>Name</th><th>Salary</th>';
$keys = array_keys($arr);
foreach ($keys as $key => $value) {
echo "$value , ";
}
for ($i=0; $i < count($arr); $i++) {
echo '<tr>';
foreach ($arr[$keys[$i]] as $key => $value) {
if ($arr[$keys[$i]['salary']] > 34000) {
echo "<td style='color: red; background-color:pink;'> $key=>$value </td>";
}else{
echo "<td> $key=>$value </td>";
}
}
echo "</tr>";
}
echo '</table>';
this is how my table looks
i want to change color of salary if it is greater than 30,000...
Change
if ($arr[$keys[$i]['salary']] > 34000) {
to
if ($value > 30000) {
I think you just got a little lost when processing an array which contains another arrays. A simple foreach loop is the simplest way of dealing with this.
echo '<table class="table table-hover"><th>Name</th><th>Salary</th>';
foreach ($arr as $row) {
echo '<tr>';
// using a ternary operator here rather than an IF
$style = $row['salary'] > 30000
? ' style="color:red;background-color:pink;"'
: '';
echo "<td>{$row['name']}</td>";
echo "<td $style>{$row['salary']}</td>";
echo '</tr>';
}

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>";

why does foreach skip 2 rows from the query result?

For 10 rows in the query it only returns 8 rows but i get the fields right:
For Query data which returns less than 2 rows I get an error.
//create table to display all data
echo "<table border="1"> ";
echo "<tr>";
$row = mysqli_fetch_assoc($result);
foreach($row as $key => $value)
{
echo "<th>$key</th>";
}
echo "</tr>";
while (($row = $result->fetch_assoc()) !== null)
{
$output = array();
$i=1;
echo "<tr>";
foreach ($row as $columnName => $columnValue)
{
$output[] = $columnName."=>". $columnValue;
echo "<td>".$columnValue."</td>";
}
echo "</tr>";
}
echo "</table>";
Edit: Thanks to #Michael Berkowski for his comments on the question.
Here is a modified version of your code that should work:
//create table to display all data
echo "<table border=1 >";
echo "<tr>";
//echo "<th> ## </th>";
$row = $result->fetch_assoc(); // stick to the object-oriented form. It is cleaner.
foreach ($row as $key => $value)
{
echo "<th>$key</th>";
}
echo "</tr>";
do
{
$output = array();
echo "<tr>";
foreach ($row as $columnName => $columnValue)
{
$output[$columnName] = $columnValue; // this is neater.
echo "<td>" . $columnValue . "</td>";
}
echo "</tr>";
} while ($row = $result->fetch_assoc());
echo "</table>";
You can use your first foreach() loop to print the keys and then use a do-while() loop to get your desired output.
Additional reading:
PHP do-while loop
You need to use
mysqli_fetch_assoc($result);

Echo all row's into table

So i have a database with 33 column's
Now this is my query :
$q3 = "SELECT * FROM qbd";
$r3 = $db1->query($q3);
while ($result = $r3->fetchAll()){
foreach($result as $row3){
echo "<tr>";
echo "<td colspan='2'>Kill ".$row3['ID']."</td>";
echo "<td>".$row3['Dragon_Bones']."</td>";
echo "<td>".$row3['Royal_Dragonhide']."</td>";
echo "</tr>";
}
}
How can i make it so that i only need to have 1 $row3 and not need to write all the column names in it?
You can try fetch() and fetch associate instead of fetchAll. Try this.
while ($result = $r3->fetch(PDO::FETCH_ASSOC)){
echo '<tr>';
foreach($result as $value){
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
You can use a second foreach to traverse to array you get as follows:
while ($result = $r3->fetchAll())
{
foreach($result as $row3)
{
echo "<tr>";
foreach($row3 as $key=>$val)
{
echo $key;
echo $val;
}
echo "</tr>";
}
}
This will display the key (column name) and the value in it.
If you want to just display the values, you can use this instead:
while ($result = $r3->fetchAll())
{
foreach($result as $row3)
{
echo "<tr>";
foreach($row3 as $key=>$val)
{
echo $val;
}
echo "</tr>";
}
}
If you are just trying to put out a table of the rows, and want the headings on the first row then you can use mysqli_data_seek() to reset the pointer back to the start after processing the first row to get the titles.
Something like this (assuming you can use mysqli_fetch_assoc):-
<?php
$q3 = "SELECT * FROM qbd";
$r3 = $db1->query($q3);
if ($result = $r3->fetch_assoc())
{
echo "<tr>";
foreach($result as $row3_key=>$row3_value)
{
echo "<td>".$row3_key."</td>";
}
echo "</tr>";
$db1->data_seek(0);
while ($result = $r3->fetch_assoc())
{
echo "<tr>";
foreach($result as $row3_key=>$row3_value)
{
echo "<td>".$row3_value."</td>";
}
echo "</tr>";
}
}
?>
EDIT - if your db class doesn't support mysqli_data_seek() (or if you are using an unbuffered query):-
<?php
$q3 = "SELECT * FROM qbd";
$r3 = $db1->query($q3);
if ($result = $r3->fetch_assoc())
{
echo "<tr>";
foreach($result as $row3_key=>$row3_value)
{
echo "<td>".$row3_key."</td>";
}
echo "</tr>";
OutputRow($result);
while ($result = $r3->fetch_assoc())
{
OutputRow($result);
}
}
function OutputRow($result)
{
echo "<tr>";
foreach($result as $row3_key=>$row3_value)
{
echo "<td>".$row3_value."</td>";
}
echo "</tr>";
}
?>
$keys = array();
$values = array();
echo '<table>';
while ($result = $r3->fetchAll()){
foreach($result as $row3){
foreach($row3 as $key=>$val){
for($i=1;$i=30;$i++){
$keys[]=$key;
}
$values[] = $val;
}
echo '<tr>';
foreach($keys as $k){
echo $k;
}
foreach($values as $v){
echo $v;
}
echo '</tr>';
}
}
echo '</table>'

Categories