PHP Multi dimentional array - php

This is my code. I don't know why it is not working.
I was trying to print my table with php for loop, but nothing shows up on the website.Nothing
This is the two-dimentional array that I was trying to print out.
<!--Arrays of weapons-->
<?php
$weapons = array(
array("M4A1",1,78906,"TUCKER, LISBETH","SPC"),
array("M4A1",2,78915,"HATHAWAY, HANNAH","1LT"),
array("M4A1",3,78933,"HARRIS, LEE","SFC"),
array("M4A1",4,78934,"WELCH, BRAD","SSG"),
array("M9",1,1167552,"BLAND, MARGARET","CPT"),
array("M249",1,101032,"TYSON, MICHELLE","1SG"),
array("M249",2,101038,"MEDINA, TOBIAS","SPC"),
array("M240B",1,104104,"COSTA, JOSHUA","SSG"),
array("M2A1",1,1863848,"GARCIA, RIGOBERTO","SSG"),
array("MK-19",1,19369,"NEUPANE, KISHOR","SPC")
);
?>
This is the code that I was trying to use to print out.
<!--Create the Weapons List Table-->
<table border ="1">
<tr>
<th>Type</th>
<th>Buttstock #</th>
<th>Serial #</th>
<th>Name</th>
<th>Rank</th>
</tr>
<!--Put two-dimentinal arrays in the table-->
<?php foreach ($row = 0; $row < 10, $row++) {?>
<tr>
<?php for ($col = 0; $col < 5, $col++) {?>
<td><?php echo $weapons[$row][$col];?></td>
<?php }?>
</tr>
<?php }?>
</table>

You have to use foreach as foreach (array_expression as $value)
The foreach construct provides an easy way to iterate over arrays.
foreach works only on arrays and objects, and will issue an error when
you try to use it on a variable with a different data type or an
uninitialized variable.
Like:
<?php
$weapons = array(
array("Type 1",1,78906,"Apple","R1"),
array("Type 2",2,78915,"Javascript","R4"),
array("Type 3",3,78933,"Red","R6"),
array("Type 4",4,78934,"Circle","R1"),
array("Type 5",1,1167552,"Fried rice","R4"),
);
?>
<table border ="1">
<tr>
<th>Type</th>
<th>Buttstock #</th>
<th>Serial #</th>
<th>Name</th>
<th>Rank</th>
</tr>
<!--Put two-dimentinal arrays in the table-->
<?php foreach ($weapons as $weapon) {?>
<tr>
<?php foreach ( $weapon as $val ) {?>
<td><?php echo $val;?></td>
<?php }?>
</tr>
<?php }?>
</table>
This will result to:
Doc: foreach

Enhancing Eddie's answer, using foreach as well,
note that you could visually simplify the code like that:
<!--Arrays of weapons-->
<?php
$weapons = array(
array("Type 1",1,78906,"Apple","R1"),
array("Type 2",2,78915,"Javascript","R4"),
array("Type 3",3,78933,"Red","R6"),
array("Type 4",4,78934,"Circle","R1"),
array("Type 5",1,1167552,"Fried rice","R4"),
);
?>
<table border ="1">
<tr>
<th>Type</th>
<th>Buttstock #</th>
<th>Serial #</th>
<th>Name</th>
<th>Rank</th>
</tr>
<!--Put two-dimentinal arrays in the table-->
<?php
foreach ($weapons as $weapon) {
echo '<tr>';
foreach ( $weapon as $val ) {
echo "<td>$val</td>";
}
echo '</tr>';
} ?>
</table>
Why using this solution?
Because the multiple opening and closing of php tags can make the code hard to read.
Documentation about foreach: http://php.net/manual/en/control-structures.foreach.php
Hope it helps.

Related

How to highlight larger value in each table row?

Below is the base code I am trying for a product comparison.
How can I highlight the larger/small value ?
For example
Consider the price as an example.
attached result screenshot
attached excel example with highlight on value
$results = $mysqli->query('SELECT * FROM filterr where pid in ('.$pid1.''.$pid2.''.$pid3.''.$pid4.') ');
?>
// SETP FOUR : Displaying table values through HTML Table
<table>
<thead>
<tr>
<th>Details</th>
<th>Model 1</th>
<th>Model 2</th>
<th>Model 3</th>
<th>Model 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Manufacturer</td>
<?php foreach ($results as $result){ ?>
<td> <?php echo $result['product_brand']; ?> </td>
<?php } ?>
<tr>
<tr>
<td>Price</td>
<?php foreach ($results as $result){ ?>
<td> <?php echo $result['product_price']; ?> </td>
<?php } ?>
<tr>
<tr>
<td>Rating</td>
<?php foreach ($results as $result){ ?>
<td> <?php echo $result['score']; ?> </td>
<?php } ?>
<tr>
<tr>
<td>Battery</td>
<?php foreach ($results as $result){ ?>
<td> <?php echo $result['battery']; ?> </td>
<?php } ?>
<tr>
<tr>
<td>Storage</td>
<?php foreach ($results as $result){ ?>
<td> <?php echo $result['product_storage']; ?> </td>
<?php } ?>
<tr>
</tbody>
</table>
you can use simple if like :
.green{background-color:green;}
<?php if( $result['product_price'] > 5000 ){ //higher then ?>
<td class='green'>
<?php }else{ ?>
<td>
<?php } ?>
You can use same method for lower with another class.

How can i manipulate array with json encoded data?

I have the array of data like:
Array
(
[0] => Array
(
[lot_no] => ["A001","A001","B002"]
[qty] => ["4","5","6"]
[weight] => ["4","5","6"]
[particular] => ["100% cashmere","100% cashmere","20% silk 80% cashmere"]
[remarks] => ["4","5","6"]
)
)
i want to throw this data in table shown in pic table no 1 like of the second pic. How can i do that?
You can iterate the loop of array in view
<?php if (count($detailListDatas ) > 0): ?>
<table>
<thead>
<tr>
<th>Sno</th>
<th>Particular</th>
<th>Lot no</th>
<th>Total Qty</th>
<th>Total Weight</th>
<th>Remark</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php $i=0;
foreach ($detailListDatas as $row) ?>
<tr>
<td><?php echo $i++?></td>
<td><?php echo $row['particular']; ?></td>
... similarly all the element
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
I tried your answer which didn't gave me the output i needed. Eventually i did it by myself like this
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>S.No</th>
<th>Particulars</th>
<th>Lot no</th>
<th>Total Qty</th>
<th>Total Weight</th>
<th>Remarks</th>
</tr>
</thead>
<tbody>
<?php $sn =1;
foreach ($detailListDatas as $key ) {
$json_array['lot_no'] = json_decode($key['lot_no'], true);
$lot_no = $json_array['lot_no'];
$i = count($lot_no);
$json_array['qty'] = json_decode($key['qty'],true);
$qty = $json_array['qty'];
$json_array['weight'] = json_decode($key['weight'],true);
$weight = $json_array['weight'];
$json_array['particular'] = json_decode($key['particular'],true);
$particular = $json_array['particular'];
$json_array['remarks'] = json_decode($key['remarks'],true);
$remarks = $json_array['remarks'];
for ($j=0; $j < $i ; $j++) { ?>
<tr>
<td><?php echo $sn?></td>
<td><?php echo $particular[$j];?></td>
<td><?php echo $lot_no[$j];?></td>
<td><?php echo $qty[$j];?></td>
<td><?php echo $weight[$j];?></td>
<td><?php echo $remarks[$j];?></td>
</tr>
<?php $sn++; } ?>
<?php } ?>
</tbody>
</table>

How to set different styles for different rows in html table created from php array?

I'm struggling with creating a html table from php array, while applying different css classes on different rows according to the array.
I have this code in data.php:
<?php
$data = array(
array('Title 1'=>'text11', 'Title 2'=>'text12'),
array('Title 1'=>'text21', 'Title 2'=>'text22'),
array('Title 1'=>'text31', 'Title 2'=>'text32'),
array('Title 1'=>'text41', 'Title 2'=>'text42', 'special'=>'style1'),
array('Title 1'=>'text51', 'Title 2'=>'text52', 'special'=>'style2'),
);
?>
I want to create a html table from this array, and if the array contains 'special'=>'style', it would set that style to that particular row. This is my code so far:
<?php include('data.php'); ?>
<table>
<thead>
<tr>
<th>Title 1</th>
<th>Title 2</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $key=>$row):
if ($row == 'class1') {
$class='class="style1"';
} elseif ($row == 'class1') {
$class='class="style2"';
} else {
$class='';
}?>
<tr <?php echo $class ?>>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
And this is the desired output:
<table>
<thead>
<tr>
<th>Title 1</th>
<th>Title 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>text11</td><td>text12</td>
</tr>
<tr>
<td>text21</td><td>text22</td>
</tr>
<tr>
<td>text31</td><td>text32</td>
</tr>
<tr class="style1">
<td>text41</td><td>text42</td>
</tr>
<tr class="style2">
<td>text51</td><td>text52</td>
</tr>
</tbody>
</table>
Your problem is this line:
<?php foreach ($data as $key=>$row):
You're forgetting that you're looping over a multidimensional array (i.e. an array of arrays) so that $row is an array here. On the next line:
if ($row == 'class1')
You're looking for a comparison between a string and $row which is an array. This will never work! As Daniel points out in his answer, you need to look at the contents of the array.
Don't forget you'll need to remove the special element from the array before displaying it. Personally, I'd condense the code a bit, though mixing PHP and HTML like this is never a good idea.
<?php include('data.php'); ?>
<table>
<thead>
<tr>
<th>Title 1</th>
<th>Title 2</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $row): $class = $row["special"] ?? ""; unset($row["special"]);?>
<tr class="<?=$class?>">
<td><?=implode("</td><td>", $row)?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
I'm not sure I understood everything but you can try this
<?php foreach ($data as $key => $row):
$class = '';
if(isset($row['special'])){
$class = 'class="'.$row['special'].'"';
unset($row['special']);
}
?>
<tr <?php echo $class ?>>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
If I understand your question correctly, this should do the job.
The result is as you desire, see: Online PHP shell
<table>
<thead>
<tr>
<th>Title 1</th>
<th>Title 2</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $key=>$row):
if (isset($row["special"])) {
$class = " class='" . $row["special"]. "'";
unset($row["special"]);
} else {
$class='';
}?>
<tr<?php echo $class ?>>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

Putting html and PHP code inside a variable

I have this code that produces a table exactly how I want it. I want to put this whole code assigned to a PHP variable e.g.: $table=the posted code. I tried concatenating and heredoc but couldn't get it to output my table as it is when doing and echo $table;.
Any input is appreciated
<table id=patients>
<tr>
<th>Pt. username</th>
<th>Pt. number</th>
<th>Full Name</th>
<th>Added on</th>
</tr>
<?php $x=1;
foreach ($users as $patient) {
?> <tr <?php if ($x % 2 == 0) {echo "class='alt'"; } ?>>
<td> <?php echo $patient['username'];?></td>
<td> <?php echo $patient['id'];?></td>
<td> <?php echo $patient['name'];?></td>
<td> <?php echo $patient['joined'];?></td>
</tr>
<?php
$x++;
} ?>
</table>
Just use output buffering to put the output into the internal buffer and then capture it.
<?php
ob_start();
?>
<table id=patients>
<tr>
<th>Pt. username</th>
<th>Pt. number</th>
<th>Full Name</th>
<th>Added on</th>
</tr>
<?php $x=1;
foreach ($users as $patient) {
?> <tr <?php if ($x % 2 == 0) {echo "class='alt'"; } ?>>
<td> <?php echo $patient['username'];?></td>
<td> <?php echo $patient['id'];?></td>
<td> <?php echo $patient['name'];?></td>
<td> <?php echo $patient['joined'];?></td>
</tr>
<?php
$x++;
} ?>
</table>
<?php
$table = ob_get_clean();
?>

Why is my table being rendered empty?

I'm writing some php that renders a table from a database, this should be simple, but for some reason, it is rendering extra cells and all cells are empty. Here is my code:
<?php
$db= new PDO("mysql:host=localhost;dbname=mydb", "user", "password");
$query= $db->query("SELECT yarnId, yarnName, longYarnDescription, sale_price, cost, contents, onSale, yarnImage, activeFlag FROM yarn");
$result= $query->fetchAll();
?>
<table border="1">
<tr>
<th>yarnId</th>
<th>yarnName</th>
<th>description</th>
<th>sale price</th>
<th>cost</th>
<th>contents</th>
<th>onSale</th>
<th>yarnImage</th>
<th>activeFlag</th>
<th>edit</th>
</tr>
<?php for($r=0; $r<count($result); $r++){?>
<tr>
<?php for($c=0; $c<count($result[0]); $c++){?>
<td><?php echo $result[r][c];?></td>
<?php }?>
<td><button name=edit>edit</button></td>
</tr>
<?php }?>
</table>
If anyone can tell me why it's empty and why there are extra cells, it would be greatly appreciated.
The following code uses while()loop instead of for()
<table border="1">
<tr>
<th>yarnId</th>
<th>yarnName</th>
<th>description</th>
<th>sale price</th>
<th>cost</th>
<th>contents</th>
<th>onSale</th>
<th>yarnImage</th>
<th>activeFlag</th>
<th>edit</th>
</tr>
<?php
while($row = $query->fetch()) {
echo "<tr>";
for ($x=0;$x<= 8; $x++) {
echo "<td>" . $row[$x] . "</td>";
}
echo "<td><button name=\"edit\">edit</button></td></tr>\n";
}
?>
</table>

Categories