PHP Find Data In Array - php

I have two seperate arrays I am using in my php page.
The first one holds all of the field names that I will be using to create my html table headers on the UI.
The array of data for this looks like so:
Array
(
[0] => Array
(
[fieldID] => 2
[fieldName] => Project Title
[fieldAlias] => initiativeTitle
)
[1] => Array
(
[fieldID] => 4
[fieldName] => Project Description (preview)
[fieldAlias] => initiativeDescriptionPreview
)
)
Next, I have a data set of all the records I need to print to the table. The key in this array matches the fieldAlais from the header array.
My goal here is to loop over the header array and get the fieldAlias, then loop over the data and when the fieldAlias from the header row matches a the key in the data row, it prints it out.
Here is how I populate the header array:
$primaryArray = Array();
if(isset($dashboardDetails->results->primary->fields)){
foreach($dashboardDetails->results->primary->fields as $p){
$primaryArray[] = array(
'fieldID' => (int)$p->fieldID,
'fieldName' => (string)$p->fieldName,
'fieldAlias' => (string)$p->alias
);
}
}
This is an example of the data object:
SimpleXMLElement Object
(
[data] => SimpleXMLElement Object
(
[initiativeDescriptionPreview] => This is a test description
[initiativeTitle] => Test
)
Here is the mess I am working with on the HTML table:
<table class="table table-hover table-striped">
<thead>
<tr>
<?php
// Loop over the primary fields
for ($i = 0; $i < count($primaryArray); ++$i) {
echo '<th class="small">'.$primaryArray[$i]['fieldName'].'</th>';
}
?>
</tr>
</thead>
<tbody>
<?php
// For each field in our primary array
for ($i = 0; $i < count($primaryArray); ++$i) {
// Set our alais
$a = $primaryArray[$i]['fieldAlias'];
echo '<tr>';
// Loop over all of the records
foreach($dashboard->data as $value){
foreach($value as $key => $val){
if($key == $a){
echo '<td class="small">'.$val.'</td>';
}
}
}
echo '</tr>';
}
?>
</tbody>
</table>
The result of this is that its printing two rows of data when this should be the same row:
The short end of this is: I have two separate objects, headers and data. I need to print the table headers and then print the data from the other array to its corresponding header.

First of all it isn't clear whether or not the data array, is an array of arrays, which it should be.
You can then loop the data array, the value of which is the row you're working with. Then you can loop the headers array, and print out the element of the row array who's key matches the value of the 'fieldAlias' element of the headers array element that your currently in.
An example:
$headers = Array(
Array(
'fieldID' => 2,
'fieldName' => 'Project Title',
'fieldAlias' => 'initiativeTitle'
),
Array(
'fieldID' => 4,
'fieldName' => 'Project Description (preview)',
'fieldAlias' => 'initiativeDescriptionPreview'
)
);
$results = new StdClass();
$results->data = Array(Array('initiativeDescriptionPreview' => 'This is a test description', 'initiativeTitle' => 'Test'));
?>
<table cellspacing="10" cellpadding="10">
<tr>
<?php foreach($headers as $headerField): ?>
<th style="border:1px solid red">
<?php echo $headerField['fieldName']; ?>
</th>
<?php endforeach; ?>
</tr>
<?php foreach($results->data as $row): ?>
<tr>
<?php foreach($headers as $headerField): ?>
<td>
<?php echo $row[$headerField['fieldAlias']]; ?>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>

Looks to me that you're creating a new <tr> element for each of your columns.
I think your HTML looks something like this:
<table class="table table-hover table-striped">
<thead>
<tr>
<th class="small">some name</th>
<th class="small">some other name</th>
</tr>
</thead>
<tbody>
<tr>
<td>value of column 1</td>
</tr>
<tr>
<td>value of column 2</td>
</tr>
</tbody>
</table>
Please notice that you probably would expect only one <tr> element in your <tbody>

I tried to create the arrays and objects, which you have described with direct PHP Code, so that I can test my approach. I think you don't need $primaryArray at all. Here is my complete solution:
<?php
$headers = array(
array("fieldID" => 2, "fieldName" => "Project Title", "fieldAlias" => "initiativeTitle"),
array("fieldID" => 4, "fieldName" => "Project Description (preview)", "fieldAlias" => "initiativeDescriptionPreview"),
);
class SimpleXMLElementObject {
public
$data;
}
$mySimpleXMLElementObject1 = new SimpleXMLElementObject;
$mySimpleXMLElementObject2 = new SimpleXMLElementObject;
$mySimpleXMLElementObject1->data = array(
"initiativeDescriptionPreview" => "This is a test description",
"initiativeTitle" => "Test"
);
$mySimpleXMLElementObject2->data = array(
"initiativeDescriptionPreview" => "This is a test description2",
"initiativeTitle" => "Test2"
);
$mySimpleXMLElementObjects = array();
$mySimpleXMLElementObjects[] = $mySimpleXMLElementObject1;
$mySimpleXMLElementObjects[] = $mySimpleXMLElementObject2;
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<table class="table table-hover table-striped">
<thead>
<?php foreach($headers as $header) { ?>
<th class="small"><?= $header["fieldName"] ?></th>
<?php } ?>
</thead>
<tbody>
<?php foreach($mySimpleXMLElementObjects as $anObject) { ?>
<tr>
<?php foreach($headers as $header) { ?>
<td class="small"><?= $anObject->data[$header["fieldAlias"]] ?></th>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
The resulting table is below:
<html>
<head>
<title>Test</title>
</head>
<body>
<table class="table table-hover table-striped">
<thead>
<th class="small">Project Title</th>
<th class="small">Project Description (preview)</th>
</thead>
<tbody>
<tr>
<td class="small">Test</th>
<td class="small">This is a test description</th>
</tr>
<tr>
<td class="small">Test2</th>
<td class="small">This is a test description2</th>
</tr>
</tbody>
</table>
</body>
</html>

Related

PHP Multi dimentional array

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.

Loop into a multidimensional array and built a table with rowspan

I have this array:
Array
(
[France] => Array
(
[0] => Array
(
[city] => Paris
)
)
[Canada] => Array
(
[0] => Array
(
[city] => Montreal
)
[1] => Array
(
[city] => Ottawa
)
)
)
Sometimes, like you can see a country can have one city (case for France) but sometimes the country can have more than one city (case for Canada).
I'm looking to have this final output:
<table>
<thead>
<tr>
<th>Country</th>
<th>Cities</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="1">France</td>
<td>Paris</td>
</tr>
<tr>
<td rowspan="2">Canada</td>
<td>Montreal</td>
</tr>
<tr>
<td>Toronto</td>
</tr>
</tbody>
</table>
Here's what I have actually:
foreach($countries as $country => $city) {
$count = count($country) ;
if($count == 1) {
echo '
<tr>
<td rowspan="1">'.$country.'</td>
<td>'.$city.'</td>
</tr>
'
}
else {
echo '
<tr>
<td rowspan="'.$count.'">'.$country.'</td>
<td>'.$city.'</td>
</tr>
<tr>
<td>'.$city.'</td>
</tr>
'
}
}
My problem is the loop and how to print the cities.
Thanks for any help.
Because you are creating a row for each city, you must loop over each city. Determining the rowspan value and whether to show the first city on the same row is simply based upon whether its the first iteration of the country's cities.
So the following code will produce your desired result:
<?php
$array = [
'France' => [
[
'city' => 'Paris'
]
],
'Canada' => [
[
'city' => 'Montreal'
], [
'city' => 'Ottawa'
],
],
];
?>
<table>
<thead>
<tr>
<th>Country</th>
<th>Cities</th>
</tr>
</thead>
<tbody>
<?php foreach ($array as $country => $city): ?>
<?php foreach (array_values($city) as $i => $value): ?>
<tr>
<?php if ($i === 0): ?>
<td rowspan="<?= count($city) ?>"><?= $country ?></td>
<?php endif ?>
<td><?= $value['city'] ?></td>
</tr>
<?php endforeach ?>
<?php endforeach ?>
</tbody>
</table>
https://3v4l.org/vp2bl
Result:
<table>
<thead>
<tr>
<th>Country</th>
<th>Cities</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="1">France</td>
<td>Paris</td>
</tr>
<tr>
<td rowspan="2">Canada</td>
<td>Montreal</td>
</tr>
<tr>
<td>Ottawa</td>
</tr>
</tbody>
</table>
For rawspan you have to check the count for the city not the count of the country.
You have to use two foreach one to country and one to city.
Below code is written using php7, for array it uses []. if you are using php 5.6 use the array definition as array().
<table>
<thead>
<tr>
<th>Country</th>
<th>Cities</th>
</tr>
</thead>
<tbody>
<?php $array = ['france' => ['paris'], 'canada' => ['montreal', 'ottawa']]; ?>
<?php foreach ($array as $country => $cities) { ?>
<tr>
<td rowspan="<?php echo (count($cities)) ?>"><?php echo $country ?></td>
<?php foreach ($cities as $index => $city) { ?>
<?php if ($index === 0) { ?>
<td><?php echo $city ?> </td></tr>
<?php } else { ?>
<tr>
<td><?php echo $city ?></td>
</tr>
<?php } ?>
<?php } ?>
<?php } ?>
</tbody>
</table>
<thead>
<tr>
<th>Country</th>
<th>Cities</th>
</tr>
</thead>
<tbody>
<?php $array = ['France' => [['city' => 'Paris']], 'Canada' => [['city' => 'Montreal'], ['city' => 'Ottawa']]]; ?>
<?php foreach ($array as $country => $cities) { ?>
<tr>
<td rowspan="<?php echo (count($cities)) ?>"><?php echo $country ?></td>
<?php foreach (array_values($cities) as $index => $value) { ?>
<?php if ($index === 0) { ?>
<td><?php echo $value['city'] ?> </td></tr>
<?php } else { ?>
<tr>
<td><?php echo $value['city'] ?></td>
</tr>
<?php } ?>
<?php } ?>
<?php } ?>
</tbody>
Try this. it should work fine
<?php
$france = array();
$canada = array();
$city1 = array('city'=>'Paris');
$city2 = array('city'=>'Montreal');
$city3 = array('city'=>'Ottawa');
array_push($france,$city1);
array_push($canada,$city2);
array_push($canada,$city3);
$country = array('France'=>$france,'Canada'=>$canada);
<table border="1" cellpadding="5" cellspacing="0">
<thead>
<th>Country </th><th> City </th>
</thead>
<tbody><?php
$flag=0;
foreach($country as $cN=>$city):?>
<tr><td rowspan="<?php echo count($city);?>"> <?php echo $cN;?></td>
<?php
if(count($city)>1)
{
foreach($city as $ckey=>$name):
if($flag)
{
?>
<tr><td> <?php echo $name['city'];?></td></tr><?php
}
else
{?>
<td> <?php echo $name['city'];?></td><?php
}
$flag = 1;
endforeach;
}
else
{
foreach($city as $ckey=>$name):?>
<td> <?php echo $name['city'];?></td><?php
endforeach;
}
?></tr><?php
endforeach;
?></tbody></table>

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>

My php loop is looping 11 times, instead of one. Cant find the bug

Here is the php code. The functions require, query and render are given to us.
<?php
// configuration
require("../includes/config.php");
$rows = CS50::query("SELECT `symbol`, `shares`, `cash` FROM `portfolios`, `users` WHERE ?", $_SESSION["id"]);
$positions = [];
foreach ($rows as $row)
{
$stock = lookup($row["symbol"]);
$total = ($stock["price"] * $row["shares"]);
if ($stock !== false)
{
$positions[] = [
"name" => $stock["name"],
"price" => $stock["price"],
"shares" => $row["shares"],
"symbol" => $row["symbol"],
"total" => $total,
"cash" => $row["cash"]
];
}
}
// render portfolio
render("portfolio.php", ["positions" => $positions, "title" => "Portfolio"]);
Here is my HTML output
<div id="middle">
<table class="table table-striped">
<thead>
<tr>
<th >Symbol</th>
<th >Name</th>
<th >Shares</th>
<th >Price</th>
<th >TOTAL</th>
</tr>
</thead>
<tbody>
<?php foreach ($positions as $position): ?>
<tr>
<td align="left" ><?= $position["symbol"] ?></td>
<td align="left" ><?= $position["name"] ?></td>
<td align="left" ><?= $position["shares"] ?></td>
<td align="left" ><?= number_format($position["price"], 2) ?></td>
<td align="left" ><?= number_format($position["total"], 2) ?></td>
</tr>
<?php endforeach ?>
<tr>
<td colspan="4" align="left">CASH</td>
<td align="left"><?= number_format($position["cash"], 2) ?></td>
</tr>
</tbody>
</table>
My guess is that there is something wrong with my foreach loop. But im not quite sure, there could also be some faults in my SQL database.
My mySQL database consist of 3 rows user_id, symbol, shares. And for my user_id I have 3 diffrent stocks with like 10 shares each.
Anyone know what could be wrong?
If it runs 7 times it means there are 7 rows returned, the foreach loop is fine. Most likely the issue is here:
$rows = CS50::query("SELECT `symbol`, `shares`, `cash` FROM `portfolios`, `users` WHERE ?", $_SESSION["id"]);
You aren't indicating which column should equal the id, so it's returning all of them likely. Need something like this:
$rows = CS50::query("SELECT `symbol`, `shares`, `cash` FROM `portfolios`, `users` WHERE portfolios.user_id = ?", $_SESSION["id"]);

Multidimensional PHP array from a MySQLi table to HTML table

I have a portion of my website where I can give awards to members. Right now I am working on creating individual description pages for each award. On that page I want to include which members have already received this award and display this data in an HTML table.
I have already passed the data into a Multidimensional array as seen below.
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$currentAward = $awardid; // Current Page Award. Local value to the page.
$result = $conn->query("SELECT * FROM vms_awardsgranted WHERE awardid='$currentAward'");
$awardsList = array();
while($pilotsList = $result->fetch_assoc()){
$awardsList[ $pilotsList["id"] ] = $pilotsList;
}
echo nl2br("DEBUG: $currentAward \n");
print_r(array_values($awardsList));
$conn->close();
?>
Example Result
DEBUG: 8
Array ( [0] => Array ( [id] => 28 [awardid] => 8 [pilotid] => 4 [dateissued] => 2015-10-14 20:12:21 ) [1] => Array ( [id] => 32 [awardid] => 8 [pilotid] => 1 [dateissued] => 2015-10-14 20:14:14 ) )
From here I am trying to parse this info and add it into the HTML table below but I honestly can't find the correct way of doing this with a Multidimensional array. Can anyone out here give me some insight? My HTML tables looks like below.
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="ocean_table">
<thead>
<tr>
<th>Pilot ID</th>
<th>Pilot Name</th>
<th>Date Awarded</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center">
</td>
<td align="center">
</td>
<td align="center">
</td>
</tr>
</tbody>
</table>
Basically, to loop through the result, your code could look like this:
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="ocean_table">
<thead>
<tr>
<th>Pilot ID</th>
<th>Pilot Name</th>
<th>Date Awarded</th>
</tr>
</thead>
<tbody>
<?php foreach($awardsList as $member):?>
<tr>
<td align="center">
<?=$pilot['pilotid']?>
</td>
<td align="center">
</td>
<td align="center">
<?=$pilot['dateissued']?>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
A couple of remarks, though.
You don't return the pilot name from the query. You should join on the table of members/pilots to get their name.
Your naming is confusing. $pilotList suggests a list of pilots, but instead that variable contains only the reference/junction between the award and one pilot. Dito for awardsList which actually contains a list of people that won the award.
Something like
<tbody>
<?php foreach($awardsList as $record){ ?>
<tr>
<td align="center">
<?php echo $record['id']; ?>
</td>
<td align="center">
<?php echo $record['awardid']; ?>
</td>
<td align="center">
<?php echo $record['pilotid']; ?>
</td>
</tr>
<?php } ?>
</tbody>

Categories