Create a bidimensional array in php - php

I confess that I am a beginner. My goal is to be able to summarize in a two-dimensional table the amount per month (in column) for each class (in line). After doing a lot of research, I arrived at this stage in my project.
My problem is , I get the result with months repeating in columns like here.
Here is my code.
This is my sql code : "SELECT classe, mois, sum_ec FROM journal"
This is my php code :
<?php
$tableau = array();
$tblClasse = array();
$rt = mysqli_query($db, $req_sit);//execute la requete
while ($row = $rt->fetch_assoc()){ //forme le tableau
$tableau[$row['classe']][$row['mois']] = $row['sum_ec'];
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
}
echo '<table border="1">
<tr>
<th> </th>';
foreach ($tblClasse as $classe) {
echo '<th>' . htmlspecialchars($classe) . '</th>';
}
echo '</tr>';
foreach ($tableau as $mois=>$value) {
echo '<tr>';
$new_line = TRUE;
foreach ($tblClasse as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
$display = isset($value[$classe]) ? $value[$classe] : " ";
echo '<td>' . $display . '</td>';
}
echo '</tr>';
}
?>
Can someone tell me what mistake I made?

The problem is in this part of your code:
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
You are adding months (Fev, Mar) to the array and trying to check if it contains classes (PS, MS etc.) which is impossible, and this condition always returns true, so Feb is added to the $tblClasse array at each iteration. You must either check months or classes and add months or classes to the array respectively. And if you want the array to contain unique values (for example, months), use keys instead of values:
if (!array_key_exists ($row['mois'],$tblClasse)) {
$tblClasse[$row['mois']] = 1;
}
Where 1 can be replaced with any other value.
In the further part of your code use the keys, not values of $tblClasse array to form the table heading.
foreach (array_keys ($tblClasse) as $mois) {
echo '<th>' . htmlspecialchars($mois) . '</th>';
}

Eureka! It worked. I just had to change the line for the values ​​to "array_keys"
foreach (array_keys($tblClasse) as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
as well and boom! It's perfect. Thank you very much my dear. You have given me a lot of happiness.

Related

PHP 'While' within a ForEach loop pulling from SQL DataBase

I have a little table being duplicated several times based on the number of entries there are in my SQL Database, which let's say is about colours. These tables will go one place to the right with each new entry. Within that, I now want, within each entry, to be able to automate an output for a few fields. For example, a single table entry might be 'reds' and now I want to display the different shades of red, i.e. 'shade1', 'shade2', 'shade3', 'shade4' from that, and then the next entry might be 'yellows' and I would want it to display as many yellows there were added, i.e. 'shade1', 'shade2'. My code is like this:
<?php
error_reporting(E_ALL ^ E_NOTICE);
$stmt = $conn->prepare("SELECT * FROM colours");
$stmt->execute();
$colours = $stmt->fetchALL();
if($colours){
$i = 1;
foreach ($colours as $key => $colour) {
$coloursrow1 .='<table >
<tr><th>' . "<b>{$colour['colour']}</b>" . '</th></tr>
<tr><td>' . "<img src='{$colour['shade1']}' />" . '</td></tr>
<tr><td>' . "<img src='{$colour['shade2']}' />" . '</td></tr>
<tr><td>' . "<img src='{$colour['shade3']}' />" . '</td></tr>
<tr><td>' . "<img src='{$colour['shade4']}' />" . '</td></tr>
</table>';
$i++;
}
}
?>
And I wondered if instead of all the lines like <tr><td>' . "<img src='../colours/reds/shade1.jpg' />" . '</td></tr>, I could put something like
if($colours){
$i = 1; $x = 1;
foreach ($colours as $key => $colour) {
$coloursrow1 .='<table >
<tr><th>' . "<b>{$colour['colour']}</b>" . '</th></tr>';
}
while ($x < 6) {
'<tr><td>' . "<img src='{$colour['shade$x']}' />" . '</td></tr>';
$x++;
}
foreach ($colours as $key => $colour) {
'</table>';
$i++;
}
}
So that it would grab and output them automatically and also giving me the ability to put a cap on how many can be output.
I tried different ways to accomplish this, but I just keep hitting dead ends. I must be doing something wrong(?)
Seems like it would be something like this, since PDO::fetchAll() returns an empty array or false on error. So just iterate over that set directly. Also, the array access is wrong, it should be {$colour['shade'.$x]}.
<?php
error_reporting(E_ALL ^ E_NOTICE);
$stmt = $conn->prepare("SELECT * FROM colours");
$stmt->execute();
$colours = $stmt->fetchALL();
foreach ($colours as $colour) {
$coloursrow1 .= "<table><tr><th><b>{$colour['colour']}</b></th></tr>";
$x = 1;
while ($x < 6) {
$coloursrow1 .= "<tr><td><img src='{$colour['shade'.$x]}' /></td></tr>";
$x++;
}
$coloursrow1 .= '</table>';
}

Auto increment through a php loop

I have a case where I am using the code below to populate a template of sorts. Within the templates' javascript I would individually check the data attribute field I setup, essentially causing me to have multiple JS files instead of one that is shared. I then thought I could use a generic name field too, but prepend a number through the loop.
For example, with the line of code below where the `name="testField". I want to see if there is a way that I can add a number, but auto increment it through the loop with php.
Is this possible?
echo '<div class="markerItem" name="testField' . $number . '" "data-marker="' . $marker_data . '">';
PHP Code
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $key=>$marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" name="testField_'.$key.'" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
Using this, $key is assigned from the array index which will be a number starting from 0 and ending at count($marker_rows)-1.
Suprisingly, I couldn't find an appropriate duplicate for this.
You can easily increment or decrement variables in PHP.
$number = 0;
foreach ($marker_rows as $marker_row) {
...
$number++; // $number will now be $number+1
}
You can use $number++ directly in your attribute (if concatenating) as this will return the current $number then increment the value.

How to format the php code to display this better

I have this code:
$sql = 'SELECT * from page';
$result = $pdo->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
if(count($result)) {
echo '<table><tr>';
foreach ($rows[0] as $columnName => $value) {
echo '<th>' . $columnName . '</th>';
}
echo '</tr>';
foreach ($rows as $row) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>' . $value . '</td>';
}
echo '<tr>';
}
echo '</table>';
}
This code is working fine. But since my table is huge, it is appearing to be very very clumsy - almost unreadable. And I don't know how to make it appear better. I tried adding spaces and tabs but to no use. I can't understand how to do it. I got this code from my friend. Can anyone modify the code so as to add at least a tab space between every column. Help would be really appreciated.
You can for example do the following:
instead of
echo '<table><tr>';
use
echo '<table border="1"><tr>';
It will put border on your table and it will be easier to differentiate between cells

PHP converting JSON file into excel table is formatted incorrectly

I have made a PHP file that takes this JSON-based file: http://www.yellowpages.com.iq/ajax/get/register/Categories.php
and converts it into an excel-formatted-table with the formatting of (.cvs) using this code :
$contents = file_get_contents('http://www.yellowpages.com.iq/ajax/get/register/Categories.php');
$data = JSON_decode($contents);
$excel_file = fopen("file.csv", "a+");
$table = "<table border='1'>";
foreach($data as $elem) {
$table .= "<tr>";
foreach($elem as $key => $prop) {
$table .= "<th>$key</th>";
$table .= "<td>$prop</td>";
fwrite($excel_file, "$key,$prop\n");
}
$table .= "</tr>";
}
$table .= "</table>";
echo $table;
But the problem being, is it takes the data and displays it correctly, although it tends to format it like so: id 1
category Advertising
id 2
category Agriculture & FoodÂ
id 3
category Air condition
id 4
category Airlines
id 5
Aluminium & Glass
Instead of what I'm trying to make it look like which I made manually:
Any help would be appreciated!
You could change the code using fputcsv, which takes care of double quotes and escaping them.
For that you need to get the JSON as an associative array (provide the second argument true):
$data = JSON_decode($contents, true);
And then the loop you have would be replaced with this:
// "loop" for the header (only 1 iteration)
foreach($data as $elem) {
$table .= "<tr><th>" . implode("</th><th>", array_keys($elem)) . "</th></tr>";
fputcsv($excel_file, array_keys($elem));
break; // only need one row for header
}
// Restart loop for the data
foreach($data as $elem) {
$table .= "<tr><td>" . implode("</td><td>", $elem) . "</td></tr>";
fputcsv($excel_file, $elem);
}

Google Analytics API v3 how to extract values?

I'm a newbie at GA API so I have no clue how to extract results the correct way in this case.
e.g. I'm trying to extract avgTimeOnPage values based on filtering from ga:pagePath = ...
But each one is returning a single digit value on ga:pagePath.. so I'm thinking the ga:pagePath and ga:avgTimeOnPage results are not being displayed correctly. Maybe I'm not extracting the right way.
Anyone who can help would be greatly appreciated.
$ids = 'ga:123456789';
// $start_date $end_date already defined
$filter = 'ga:pagePath==/folder/somepage.html';
$metrics = 'ga:avgTimeOnPage';
$optParams = array('dimensions' => 'ga:pagePath', 'filters' => $filter);
$data = $service->data_ga->
get($ids, $start_date, $end_date, $metrics, $optParams);
foreach($data['totalsForAllResults'] as $rows) :
echo $rows['ga:pagePath']; // why returning a single digit value?
echo $rows['ga:avgTimeOnPage']; // also returns a single digit
endforeach;
$data['totalsForAllResults'] will return a single row that is the total row. You are looking for the values not the totals. so you should use:
foreach ($data->getRows() as $row) :
And then you can iterate $rows for every cell.
Check this full example:
private printDataTable(&$results) {
if (count($results->getRows()) > 0) {
$table .= '<table>';
// Print headers.
$table .= '<tr>';
foreach ($results->getColumnHeaders() as $header) {
$table .= '<th>' . $header->name . '</th>';
}
$table .= '</tr>';
// Print table rows.
foreach ($results->getRows() as $row) {
$table .= '<tr>';
foreach ($row as $cell) {
$table .= '<td>'
. htmlspecialchars($cell, ENT_NOQUOTES)
. '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
} else {
$table .= '<p>No Results Found.</p>';
}
print $table;
}
source: https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide#working

Categories