Parsing Multidimensional Array in PHP - php

Apologies if this is a duplication of another answer, I have spent a considerable amount of time looking through this and other forums without finding an explanation that makes sense to my very small brain.
I have a multi-dimensional array that I need to parse through using PHP:
Array
(
[dataSetOut] => Array
(
[diffgram] => Array
(
[anonymous] => Array
(
[maindb_productionhistory] => Array
(
[0] => Array
(
[z_internal_sequence] => 1
[z_internal_groupid] => 0
[z_internal_colorbg] => 15461355
[z_internal_colorfg] => 0
[maindb_productionhistory_operation] => 0402D04
[maindb_productionhistory_date] => 2014-02-19T00:00:00+00:00
[maindb_productionhistory_shift] => 1
[maindb_productionhistory_transcode] => 33
[maindb_productionhistory_qty] => 153
[!diffgr:id] => maindb_productionhistory1
[!msdata:rowOrder] => 0
)
[1] => Array
(
[z_internal_sequence] => 2
[z_internal_groupid] => 0
[z_internal_colorbg] => 16777215
[z_internal_colorfg] => 0
[maindb_productionhistory_operation] => 0402D04
[maindb_productionhistory_date] => 2014-02-19T00:00:00+00:00
[maindb_productionhistory_shift] => 1
[maindb_productionhistory_transcode] => 34
[maindb_productionhistory_qty] => 6
[!diffgr:id] => maindb_productionhistory2
[!msdata:rowOrder] => 1
)
)
)
)
)
[errorMessage] =>
)
I am looking to output a table like:
Operation | Date | Qty
0402D04 | 2014-02-19 | 153
0402D04 | 2014-02-19 | 6

<table>
<thead>
<tr>
<th>Operation</th>
<th>Date</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<?php
foreach($array['dataSetOut']['diffgram']['anonymous']['maindb_productionhistory'] as $val){
echo "<tr>";
echo "<td>".$val['maindb_productionhistory_operation']."</td>";
echo "<td>".date('Y-m-d',strtotime($val['maindb_productionhistory_date']))."</td>";
echo "<td>".$val['maindb_productionhistory_qty']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>

Related

Convert Array to html table in php

I have an array generated by an API i use a cpanel hosting with php 5.6.
I tried a lot of combination but is not working
The array are generated by emag marketplace api.
The code looks like
Array
(
[isError] =>
[messages] => Array
(
)
[results] => Array
(
[0] => Array
(
[vendor_name] => WISE COMPUTER SRLD
[id] => 2003677675
[parent_id] =>
[date] => 2017-05-21 10:55:18
[payment_mode] => RAMBURS
[payment_mode_id] => 1
[delivery_mode] => CURIER RO
[observation] =>
[status] => 4
[payment_status] => 0
[customer] => Array
(
[id] => 994041
[mkt_id] => 994041
[name] => Cristina Manuela Dancas
[company] => Cristina Manuela Dancas
[gender] =>
[phone_1] => 0743073616
[phone_2] =>
[phone_3] =>
[registration_number] =>
[code] =>
[email] =>
[billing_name] =>
[billing_phone] =>
[billing_country] => RO
[billing_suburb] => Bucuresti
[billing_city] => Sectorul 1
[billing_locality_id] => 2
[billing_street] => Str. Aviator Sanatescu nr. 57, parter, Ap1
[billing_postal_code] =>
[shipping_country] => RO
[shipping_suburb] => Bucuresti
[shipping_city] => Sectorul 1
[shipping_locality_id] => 2
[shipping_postal_code] =>
[shipping_contact] => Cristina Manuela Dancas
[shipping_phone] => 0743073616
[created] => 2017-05-21 10:55:19
[modified] => 2017-05-21 10:56:21
[bank] =>
[iban] =>
[legal_entity] => 0
[fax] =>
[is_vat_payer] => 1
[liable_person] =>
[shipping_street] => Str. Aviator Sanatescu nr. 57, parter, Ap1
)
I what to use php to convert in a HTML table.
Need some help. If you need more information please leave a message.
This is my quick solution to make a HTML table from a PHP array.
The essence is although, that a two-dimensional array, makes into a table that makes sense. Your array seems to be more complex, so converting into a useful table will probably take a bit more effort.
$data = array( array("ID","Firstname","Lastname","Phone"),
array("1","John","Jenkins","+91375953"),
array("2","Eduard","Kenny","+7244277"),
array("3","Anita","Beaumont","+427427427"),
array("4","Wanda","Wade","+274274247"),
array("4","Sarah","Colon","+835835"),
);
echo '<table border="1">';
foreach($data as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</table>';

PHP Multidimensional Array to Two Column HTML Table

I have an array called $data and I would like to display a two column html table,
tableHeader on the left hand column.
tableData on the right hand column.
A print_r($data) displays the following
Array
(
[0] => Array
(
[tableHeader] => ID
[tableData] => 104
)
[1] => Array
(
[tableHeader] => Member Number
[tableData] => not available
)
[2] => Array
(
[tableHeader] => First Name
[tableData] => Peter
)
[3] => Array
(
[tableHeader] => Last Name
[tableData] => Keys
)
[4] => Array
(
[tableHeader] => Address
[tableData] => 17 main road
)
[5] => Array
(
[tableHeader] => Email
[tableData] => P3TER#HOTMAIL.CO.UK
)
[6] => Array
(
[tableHeader] => Post Code
[tableData] => LDN 1
)
[7] => Array
(
[tableHeader] => City
[tableData] => London
)
[8] => Array
(
[tableHeader] => Year Graduated
[tableData] => 0000-00-00
)
[9] => Array
(
[tableHeader] => Subject Studied
[tableData] => Comp
)
[10] => Array
(
[tableHeader] => Telephone Number
[tableData] => 123123
)
)
I have tried the following foreach loop but I keep receiving an error message;
Message: Undefined variable: value
<table class="table">
<thead>
<? foreach ($data as $value): ?>
<tr>
<th scope="col"><?php echo $value['tableHeader']; ?></th>
</tr>
<? endforeach; ?>
</thead>
<tbody>
<? foreach ($data as $value): ?>
<tr>
<th scope="col"><?php echo $value['tableData']; ?></th>
</tr>
<? endforeach; ?>
</tbody>
</table>
What am I doing wrong?
It looks like the short tags are not working, because when the php code inside of the foreach loop is executed, it does not recognise the $value variable, because it was never parsed by php.

Reconstruct PHP array to fit data into html table correctly

I'm trying to display data that shows the count for each month for locations in Jan-December.
I wrote the query to get the necessary data from the server but when I display it in the view in my table the layout for the data, doesn't look the way I want it to look like in my table. I believe I have to reconstruct the array that I wrote in the query for the right format first and then I can display it in my table?
Right now, the data that comes back from the server looks like so
<table id="registeredTable" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Locations</th>
<th>January</th>
<th>Feburary</th>
<th>March</th>
<th>April</th>
<th>May</th>
<th>June</th>
<th>July</th>
<th>August</th>
<th>September</th>
<th>October</th>
<th>November</th>
<th>December</th>
</tr>
</thead>
<tbody>
<?php
foreach($selectAllmonthlylocations as $item) {
echo '
<tr>
<td>'.$item["locations"].'</td>
<td>'.$item["Total"].'</td>
</tr>
';
}
?>
</tbody>
</table>
So my question is how can I format my array properly to display it in my table how I want?
Array
(
[0] => Array
(
[usergroup] => Austin_Domestic
[DateAdded] => 2018-01-03
[Total] => 15
)
[1] => Array
(
[usergroup] => Austin_International
[DateAdded] => 2018-01-25
[Total] => 2
)
[2] => Array
(
[usergroup] => BayArea_Domestic
[DateAdded] => 2018-01-16
[Total] => 192
)
[3] => Array
(
[usergroup] => BayArea_International
[DateAdded] => 2018-01-05
[Total] => 28
)
[4] => Array
(
[usergroup] => Bengaluru_Domestic
[DateAdded] => 2018-01-10
[Total] => 2
)
[5] => Array
(
[usergroup] => Bengaluru_International
[DateAdded] => 2018-01-05
[Total] => 1
)
[6] => Array
(
[usergroup] => Cork
[DateAdded] => 2018-01-02
[Total] => 31
)
[7] => Array
(
[usergroup] => CulverCity
[DateAdded] => 2018-01-10
[Total] => 3
)
[8] => Array
(
[usergroup] => Denver
[DateAdded] => 2018-01-10
[Total] => 1
)
[9] => Array
(
[usergroup] => Hyderabad
[DateAdded] => 2018-01-05
[Total] => 3
)
[10] => Array
(
[usergroup] => London
[DateAdded] => 2018-01-02
[Total] => 10
)
[11] => Array
(
[usergroup] => Macau
[DateAdded] => 2018-01-17
[Total] => 1
)
[12] => Array
(
[usergroup] => Munich
[DateAdded] => 2018-01-02
[Total] => 6
)
[13] => Array
(
[usergroup] => Sacramento_Domestic
[DateAdded] => 2018-01-04
[Total] => 1
)
[14] => Array
(
[usergroup] => Shanghai
[DateAdded] => 2018-01-12
[Total] => 2
)
[15] => Array
(
[usergroup] => Singapore
[DateAdded] => 2018-01-03
[Total] => 8
)
[16] => Array
(
[usergroup] => Sydney
[DateAdded] => 2018-01-21
[Total] => 1
)
[17] => Array
(
[usergroup] => Tokyo
[DateAdded] => 2018-01-04
[Total] => 3
)
[18] => Array
(
[usergroup] => Austin_Domestic
[DateAdded] => 2018-02-01
[Total] => 31
)
[19] => Array
(
[usergroup] => Austin_International
[DateAdded] => 2018-02-19
[Total] => 2
)
[20] => Array
(
[usergroup] => Bangkok
[DateAdded] => 2018-02-07
[Total] => 1
)
[21] => Array
(
[usergroup] => BayArea_Domestic
[DateAdded] => 2018-02-08
[Total] => 165
)
[22] => Array
(
[usergroup] => BayArea_International
[DateAdded] => 2018-02-12
[Total] => 29
)
Here is my code:
$selectallmonthlysql = 'SELECT locations, DateAdded, COUNT(*) as Total
FROM testserverdataSignup
WHERE DateAdded > "2017-12-31"
GROUP BY month(DateAdded), locations';
$selectAllmonthlystmt = $dbo->prepare($selectallmonthlysql);
$selectAllmonthlystmt->execute();
$selectAllmonthlylocations = $selectAllmonthlystmt->fetchAll(PDO::FETCH_ASSOC);
Screenshot of what the table currently looks like: I want the individual count for each location to correlate to the month and go across instead of down
First change your query
$selectallmonthlysql = '
SELECT
locations,
MONTHNAME(DateAdded) AS month,
COUNT(*) AS total
FROM
testserverdataSignup
WHERE
DateAdded > "2017-12-31"
GROUP BY month(DateAdded),locations';
I lowercased Total to total, its something that was irritating me.
With PDO then you can do
$results = $selectAllmonthlystmt->fetchAll(PDO::FETCH_GROUP);
foreach($results AS $location => $row ){
FETCH_GROUP is poorly documented but this will organize your data with the first column as the Key of the nested array, in this case the location, which is exactly what we want. One of the reasons I use PDO instead of that other DB library I won't mention by name but it starts with MySql and ends with i.
MONTHNAME (click for documentation) will return the full name of the month like "February" which although is not necessary (just a number would do) its much easier to read when outputting the array for debugging.
You'll wind up with something like this
//canned example data, notice one month is out of order and the big gap
// between February to October, this is to show it properly orders and
//fills those in. Always best to test this situations.
$result = array(
"Austin_Domestic" => array(
0 => Array(
"month" => "February",
"total" => 5
),
1 => Array(
"month" => "January",
"total" => 15
),
2 => Array(
"month" => "October",
"total" => 8
),
),
);
//$results = $selectAllmonthlystmt->fetchAll(PDO::FETCH_GROUP);
//then putting it all together
//we'll need the months in an array anyway so we can saves some space with them in the HTML too.
$months = array(
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
)
?>
<table id="registeredTable" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Locations</th>
<?php foreach($months as $month){
//Output the names of the months
echo "<th>{$month}</th>\n";
} ?>
</tr>
</thead>
<tbody>
<?php
foreach( $result as $location => $rows ){
echo "<tr>\n";
echo "<td>{$location}</td>\n";
//simplifies lookup by month (indexes are correlated)
//it returns column 'month' from $rows as a flat array.
//we can save ourselves an external loop by doing this "trick"
$m = array_column($rows, 'month');
//for example, in the case: [0=>February,1=>January,2=>October]
//because this is created from $rows, with a natural number index
//we can simply do array_search on $m to get the index we need in $rows (see below)
foreach($months as $month){
$index = array_search($month, $m);
if(false === $index){
echo "<td>0</td>\n";
}else{
echo "<td>{$rows[$index]['total']}</td>\n";
}
}
echo "</tr>\n";
}
?>
</tbody>
</table>
Output (I did format it to look a bit nicer):
<table id="registeredTable" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Locations</th>
<th>January</th>
<th>February</th>
<th>March</th>
<th>April</th>
<th>May</th>
<th>June</th>
<th>July</th>
<th>August</th>
<th>September</th>
<th>October</th>
<th>November</th>
<th>December</th>
</tr>
</thead>
<tbody>
<tr>
<td>Austin_Domestic</td>
<td>15</td>
<td>5</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>8</td>
<td>0</td>
<td>0</td>
</tr>
</tbody>
</table>
Sandbox
One note and benefit of using an array for the months is you spelled Feburary wrong it should be February something I've been guilty of many many times.
The only real downside to this, is the month name has to match the month name returned from the DB, which shouldn't be an issue if they are spelled correctly (which is how I found the mistake). Otherwise this can applied to the month as a number just as easily, same idea.
Cheers!
First, you should change the query to return MONTH(DateAdded) instead of the whole date, since that's how your output table is organized:
$selectallmonthlysql = 'SELECT locations, MONTH(DateAdded) AS month, COUNT(*) as Total
FROM testserverdataSignup
WHERE DateAdded > "2017-12-31"
GROUP BY month, locations';
Then you should reorganize the array into nested arrays:
array(location1 => array(month1 => total1, month2 => total2, ...),
location2 => array(month1 => total1, month2 => total2, ...),
...)
This code will do that:
$groupedData = array();
while ($selectAllmonthlystmt->fetch(PDO::FETCH_ASSOC) {
$groupedData[$row['locations']][$row['month']] = $row['Total'];
}
Then you can use nested loops when creating the table. The outer loop creates the rows, the inner loop is for the cells in the row.
foreach ($groupedData as $location => $locationData) {
echo "<tr><td>$location</td>";
for ($month = 1; $month <= 12; $month++) {
echo "<td>";
echo isset($locationData[$month]) ? $locaitonData[$month] : 0;
echo "</td>";
}
echo "</tr>";
}

create table from array with dynamic headers and data

I am trying to create a table from array retrieved from database.
array is multidimensional and dynamic.
my sample array is
Array
(
[0] => Array
(
[licensee] => AmazonUK
[totalCounts] => 2
[netRoyalty] => 0.01006506
[month] => 2017-05-01
)
[1] => Array
(
[licensee] => AppleMusicGB
[totalCounts] => 52
[netRoyalty] => 43.39295886
[month] => 2017-04-01
)
[2] => Array
(
[licensee] => AppleMusicHK
[totalCounts] => 2
[netRoyalty] => 6.71799264
[month] => 2017-05-01
)
[3] => Array
(
[licensee] => AppleMusicIN
[totalCounts] => 22
[netRoyalty] => 1.29255252
[month] => 2017-03-01
)
[4] => Array
(
[licensee] => AppleMusicUS
[totalCounts] => 192
[netRoyalty] => 328.95685302
[month] => 2017-03-01
)
[5] => Array
(
[licensee] => Deezer
[totalCounts] => 18
[netRoyalty] => 2.91837036
[month] => 2017-01-01
)
[6] => Array
(
[licensee] => GoogleLocker
[totalCounts] => 10
[netRoyalty] => 0.08685774
[month] => 2017-01-01
)
[7] => Array
(
[licensee] => GoogleSubscription
[totalCounts] => 30
[netRoyalty] => 57.13748172
[month] => 2017-03-01
)
[8] => Array
(
[licensee] => Spotify
[totalCounts] => 356
[netRoyalty] => 179.53991898
[month] => 2017-03-01
)
[9] => Array
(
[licensee] => iTunesAU
[totalCounts] => 14
[netRoyalty] => 3.14949396
[month] => 2017-02-01
)
[10] => Array
(
[licensee] => iTunesCA
[totalCounts] => 16
[netRoyalty] => 0.18564444
[month] => 2017-01-01
)
[11] => Array
(
[licensee] => iTunesEU
[totalCounts] => 4
[netRoyalty] => 1.00737582
[month] => 2017-02-01
)
[12] => Array
(
[licensee] => iTunesGB
[totalCounts] => 8
[netRoyalty] => 0.91430508
[month] => 2017-03-01
)
[13] => Array
(
[licensee] => iTunesUS
[totalCounts] => 2
[netRoyalty] => 99.69851988
[month] => 2017-06-01
)
)
I want to create a table like :
licensee as horizontal heading
month as vertical heading
totalCounts and netRoyalty as totalCounts/netRoyalty under their respective licensee
jsfiddle of sample table is included.
jsfiddle
EDIT :
what i tried is
<table id="table1" class="table table-striped table-hover table-fw-widget">
<thead>
<tr>
<?php
foreach($distributorReportAnalysis as $distreportkey => $distreportval){
?>
<th><?php echo $distreportval[licensee]; ?></th>
<?php
}
?>
</tr>
</thead>
<tbody>
<?php
foreach($distributorReportAnalysis as $distreportk => $distreportv){
?>
<tr class="odd gradeX">
<th><?php echo date('M Y',strtotime($distreportv[month])); ?></th>
<?php
foreach($distreportv as $reportk => $reportv){
?>
<td><?php echo $distreportv['totalCounts']."/".round($distreportv['netRoyalty']); ?></td>
<?php
}
?>
</tr>
<?php
}
?>
</tbody>
</table>
this is a quick example of how you could extract values with array_map. Actually a foreach works too, array_map is particularly useful if you want to modify the original array.
So the idea here is to organize the data before display, here getting the headers and value by month separately. For your display, you'll still have to place the good value to the good position in the array, but it is sorted by headers value now, so that will be easy.
<?php
$arr = [
0 => [
'licensee' => 'AmazonUK',
'totalCounts' => '2',
'netRoyalty' => '0.01006506',
'month' => '2017-05-01',
],
1 => [
'licensee' => 'AppleMusicGB',
'totalCounts' => '52',
'netRoyalty' => '43.39295886',
'month' => '2017-04-01',
],
];
$headers = [];
$rows = [];
function customExtract($element){
global $headers, $rows;
//an array for your headers
if(!in_array($element['licensee'], $headers)){
$headers[] = $element['licensee'];
}
//another for the rows by month
if(!isset($rows[$element['month']])){
$rows[$element['month']] = [];
}
$rows[$element['month']][$element['licensee']] = $element['totalCounts'] . '/' . $element['netRoyalty'];
//you can also transform the original array element or not (if not you just return it)
return $element;
}
$arr = array_map('customExtract', $arr);
var_dump($headers);
echo'<br />';
var_dump($rows);
?>
the result:
array(2) { [0]=> string(8) "AmazonUK" [1]=> string(12) "AppleMusicGB" }
array(2) { ["2017-05-01"]=> array(1) { ["AmazonUK"]=> string(12) "2/0.01006506" } ["2017-04-01"]=> array(1) { ["AppleMusicGB"]=> string(14) "52/43.39295886" } }

Data from array into html combobox

I have 2 arrays inside the class Continente..both public and i populate the arrays with records from mysql database.
class Continente{
public $continente = array();
public $tari= array();
}
And i have an object for wich i call the methods to put data into my arrays.
$cont = new Continente;
$cont->setContinente();
$cont->setTari();
Now the arrays look like this:
Array (
[0] => Array ( [Id] => 1 [Nume] => Europa )
[1] => Array ( [Id] => 2 [Nume] => Asia )
[2] => Array ( [Id] => 3 [Nume] => Africa ) )
and:
Array
( [0] => Array ( [Id] => 0 [Nume] => Romania [idContinent] => 1 [Populatie] => 2500 )
[1] => Array ( [Id] => 0 [Nume] => Bulgaria [idContinent] => 1 [Populatie] => 2200 )
[2] => Array ( [Id] => 0 [Nume] => Estonia [idContinent] => 1 [Populatie] => 1100 )
[3] => Array ( [Id] => 0 [Nume] => Japonia [idContinent] => 2 [Populatie] => 5000 )
[4] => Array ( [Id] => 0 [Nume] => China [idContinent] => 2 [Populatie] => 4599 )
[5] => Array ( [Id] => 0 [Nume] => India [idContinent] => 2 [Populatie] => 6000 )
[6] => Array ( [Id] => 0 [Nume] => Egipt [idContinent] => 3 [Populatie] => 444 ) )
now i need to make a combox with the 3 continents , and for each continent selected i need to print the first 3 countries sorted by the bigest number in 'Populatie' .
So i can select the contries for the continents... i have Id=idContinent .
Now i really don't know how to do this. Write a method for this in php? As i already have the arrays... or html?
This is what i tried:
<html>
<head></head>
<body>
<div>
<br>
<select>
<?php
foreach($cont->tari as $val ){
echo '<option value="'.$val.'">'.$val.'</option>';
}
?>
</select>
</div>
</body>
</html>
If you can do it, I think you can clean up your data structure quite a bit and it would make it easier to accomplish what you are trying to do. If you store your information like this:
$data = array( Europa => array (Romania => 2500,
Bulgaria => 2200,
Estonia => 1100 ),
Asia => array ( Japonia => 5000,
China => 4599,
India => 6000 )
...);
Then you may be able to eliminate the need for your "ID" keys and just use the array indices for your IDs.
Then you can just sort your subarrays by value using arsort(). Something like this:
foreach( $data as $cont => $pop_data ) {
arsort( $pop_data );
}
Then for creating your combo boxes, use similar code:
foreach( $data as $cont => $pop_data ) {
echo $cont . " Population Info:" . "<br>"; // or whatever
foreach( $pop_data as $country => $pop ) {
echo '<option value="'.$pop.'">'.$pop.'</option>';
}
}

Categories