PHP blog categories duplication - php

I have got a question regarding setting up proper categories for my posts that would be done automatically. I'm using PHP.
Here is my sample example document from the database:
{
"_id" : "css-clearfix-explained",
"title" : "CSS Clearfix Explained",
"category" : [
"CSS/HTML",
" Wordpress"
],
"date_time" : ISODate("2014-08-13T21:03:45.367Z"),
"description" : "Blalalal ",
"content" : " ",
"author" : "Maciej Sitko"
}
So, for that purpse I wrote the code that inserts the categories in the view page, to be more specific, it inserts them into the table. This is the code:
<?php if(!isset($_GET['cat'])) {
$categories = $collection->find();?>
<table class="table table-hover table-striped">
<thead class='table-head' >
<tr ><th colspan='2'>Categories</th></tr>
</thead>
<tbody>
<?php foreach($categories as $category) {
foreach($category as $keys) {
if((is_array($keys)) && (!empty($keys))) {
foreach($keys as $key => $value) { ?>
<tr>
<td><a class="normalize" href="">
<?php echo $keys[$key]; ?></a></td>
<td class="small"> Posts</td>
</tr>
<?php } } } } ?>
</tbody>
</table>
The problem is, and you see it (I bet it), that when it is executed this way there would be duplicates of the categories in the table shown. How can I prevent those categories from repeating themselves in the listing? I know its a rookie question, but I'm still learning.

You could write $category into an array and every iteration - before displaying your data - you could check if $category is already in there. You could use "in_array": http://php.net/manual/de/function.in-array.php
<?php if(!isset($_GET['cat'])) {
$categories = $collection->find();?>
<table class="table table-hover table-striped">
<thead class='table-head' >
<tr ><th colspan='2'>Categories</th></tr>
</thead>
<tbody>
<?php
$uniqueCats = array();
foreach($categories as $category) {
foreach($category as $keys) {
if((is_array($keys)) && (!empty($keys))) {
foreach($keys as $key => $value) {
if( in_array($value, $uniqueCats) ) { continue; }
$uniqueCats[] = $value;
?>
<tr>
<td><a class="normalize" href="">
<?php echo $value; ?></a></td>
<td class="small"> Posts</td>
</tr>
<?php } } } } ?>
</tbody>
</table>
I hope that's what you were looking for :)
The code/variables slightly differs from how I would read the data in the example so I might have misinterpreted your question :)

Related

Table Not Rendering Properly with Async | PHP | API | LARAVEL

I have this async code , but when i try to render inside a table , the table become a mess (image) but after a page refresh the table is perfctly fine and i dont know why , how can i fix this problem ?
and if is possible to have a better async code , i know i need to async the
$api->getMatchTimeline($match->gameId); but i don't know how can i do it.
<table class="table table table-bordered" style="width:100%">
<tr>
<thead>
<th>Items</th>
</thead>
</tr>
<tbody>
<?php
$onSuccess = function (Objects\MatchDto $match) use (&$api, $champ) {
echo "<tr>";
echo "<td>";
foreach ($match->participants as $partId) {
if ($partId->championId == $champ) {
$participant_id = $partId->stats->participantId;
$pp = $api->getMatchTimeline($match->gameId);
foreach ($pp->frames as $p) {
foreach ($p->events as $t) {
if ($t->type == "ITEM_PURCHASED" and $t->participantId == $participant_id) {
$item_id = $t->itemId;
$d = $api->getStaticItem($item_id);
$depth = $d->depth;
if (($depth == 3 or $depth == 2)) {
echo "<a href = https://lolprofile.net/match/kr/$match->gameId#Match%20History >";
echo "<img src =" . DataDragonAPI::getItemIconUrl($item_id) . " />" . '</a>';
}
}
}
}
}
}
echo "</td>";
echo "</tr>";
};
$onFailure = function ($ex) {
echo $ex;
};
foreach ($database as $game) {
$api->nextAsync($onSuccess);
$match = $api->getMatch($game->match_ids);
}
$api->commitAsync();
?>
</tbody>
</table>
render outside the table
The problem isn't to do with your "async" PHP code, but because your <table> markup is incorrect.
HTML's <table> element has two different forms. The first is the "implicit <tbody> form, like this:
<table>
<tr>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
</table>
The other has an explicit <tbody> element, which can also optionally have a <thead> and <tfoot> (you can also have multiple <tbody> but only a single <thead>. You can use a <thead> and <tfoot> with an implicit <tbody> but this is not recommended - I recommend everyone use the explicit syntax, like so:
<table>
<tbody>
<tr>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
</tbody>
</table>
Note that the actual DOM representation of both tables is the same: in the DOM a <table> never has <tr> as immediate children.
Secondarily, you can also make your code a LOT easier to read and follow if you separate your application logic from your rendering logic by doing all of your API calls and whatnot at the start of your PHP script and populate a "view model" object and then the rendering logic is greatly simplfied, like so:
<?php
// This PHP block should be before *any* HTML is written:
class MatchAndItems {
public Objects\MatchDto $match;
public Array $items;
}
$allMatches = Array(); # Array of `MatchAndItems`.
$onFailure = function ($ex) {
echo $ex;
};
$gotMatch = function (Objects\MatchDto $match) use (&$api, $champ, $allMatches) {
$e = new MatchAndItems();
$e->match = $match;
$e->items = array();
foreach ($match->participants as $partId) {
if ($partId->championId == $champ) {
$participant_id = $partId->stats->participantId;
$pp = $api->getMatchTimeline($match->gameId);
foreach ($pp->frames as $p) {
foreach ($p->events as $t) {
if ($t->type == "ITEM_PURCHASED" and $t->participantId == $participant_id) {
$item_id = $t->itemId;
$d = $api->getStaticItem($item_id);
array_push( $e->items, $d );
}
}
}
}
}
array_push( $allMatches, $e );
};
# Set-up web-service HTTP request batches:
foreach( $database as $game ) {
$api->nextAsync( $gotMatch )->getMatch( $game->match_ids );
}
# Invoke the batch:
$api->commitAsync();
# The below code uses https://www.php.net/manual/en/control-structures.alternative-syntax.php
?>
<!-- etc -->
<table class="table table table-bordered" style="width: 100%">
<thead>
<tr>
<th>Items</th>
</tr>
</thead>
<tbody>
<?php foreach( $allMatches as $match ): ?>
<tr>
<td>
<?php
foreach( $match->items as $item ):
if( $item->depth == 2 or $item->depth == 3 ):
echo "<a href = https://lolprofile.net/match/kr/$match->gameId#Match%20History >";
echo "<img src =" . DataDragonAPI::getItemIconUrl($item_id) . " />" . '</a>';
endif;
endforeach;
?>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>

dataTables, nested tables foreach

I have a problem with datatable, it's working but it's not working right..
I have the next code:
<table id="dt_basic" class="table table-striped table-bordered table-hover" width="100%">
<thead>
<tr>
<th>Codigo PT</th>
<th><i class="text-muted hidden-md hidden-sm hidden-xs"></i>Producto Terminado</th>
</tr>
</thead>
<tbody>
<?php
foreach ($registros as $reg)
{
?>
<tr style="border-bottom:2px solid #000;background: #cee8ff;">
<td><?php echo $reg -> id_codigo;?></td>
<td><?php echo utf8_encode($reg ->id_product_term);?></td>
</tr>
<?php
$AllRows = $_interfaz -> get_all($reg -> id_interfaz);
foreach ($AllRows as $row)
{
?>
<tr>
<td><b style="font-size:20px;">—</b></td>
<td><?php echo $row -> id_product_term;?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
It has a forearch() { forearch() { } } two foreach, a nested foreach.
The problem is that the datatable put the first foreach result at last and the result of the nested (SECOND) foreach in the beginning, like this:
second foreach result
second foreach result
second foreach result
first foreach result
first foreach result
first foreach result
why does datable organize the table as above?
why does not it do this?:
first foreach result
second foreach result
first foreach result
second foreach result
first foreach result
second foreach result
because one foreach is nested..
how can i fix it?
my js script is:
$('#dt_basic').dataTable({
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
"autoWidth" : true,
"oLanguage": {
"sSearch": '<span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span>'
}});
Thanks.
why does datable organize the table as above?
Because dataTables is ordering the rows by default as [[0, 'asc']]. Thats why all your rows with
<tr><td><b style="font-size:20px;">—</b></td>...</tr>
is shown first. There is a extension called rowGroup which purpose is exactly what you are trying to do. Include the rowGroup source, then add an extra invisible column to group by :
<tr style="border-bottom:2px solid #000;background: #cee8ff;">
<td><?php echo $reg -> id_codigo;?></td>
<td><?php echo $reg -> id_codigo;?></td>
<td><?php echo utf8_encode($reg ->id_product_term);?></td>
</tr>
...
<tr>
<td><?php echo $reg -> id_codigo;?></td>
<td><b style="font-size:20px;">—</b></td>
<td><?php echo $row -> id_product_term;?></td>
</tr>
Make the new group column invisible and rowGroup that column :
$('#dt_basic').dataTable({
columnDefs: [
targets: 0, visible: false }
],
rowGroup: {
dataSrc: 0
}
...
})
Here is an example of using rowGroup upon an invisible column -> http://jsfiddle.net/8r88gsfk/

Selected Data only post within the same page PHP CodeIgniter

i have paging data table with checkbox on it,when i selected the checkbox,it only post the selected checkbox in the same page,here is my view :
<label>Category</label>
<select name="cat" id="cat>
<option value="Motorcycle">Motorcycles</option>
<option value="Motorcycle">Cars</option>
</select>
<table id="tabelgg" class="table table-bordered">
<thead>
<tr>
<th>NO.</th>
<th>NAME</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<?php
$no=1;
foreach ($cats as $data) {
echo "<tr>";
echo "<td>".$no."</td>";
echo "<td>".$data['name']."</td>";
echo "<td><center><input type='checkbox' name='desc[]' id='desc[]' value='".$data['id_list']."'></center></td></td>";
echo "</tr>";
$no++;
}
?>
</tbody>
</table>
and this is my save controller
if(isset($_POST['desc']))
{
if (is_array($_POST['desc']))
{
foreach($_POST['desc'] as $check){
$data_=array('cat' => $this->input->post('cat'),
'item_head' => $check);
}
} else {
$value = $_POST['ket'];
echo $value;
}
$this->db->insert('tbl_pengelompokan',$data_);
}
redirect('admin/pengelompokan','location');
how do i make change for my controller view so it will post one-to-many data ?
You can use DataTable javascript plugin to do that. I use server side script to show many data as well on one request as dynamic.

How to make numbering navigation after break; in PHP?

Hi all I have searching for method but not luck. Help me I want to make numbering navigation. Here is my code:
<ul>
<?php
$kw = file_get_contents('keywords.txt');
$kw = explode("\n", $kw);
asort($kw);
$i = 0;
foreach($kw as $k) {
if($i==30) { break; }
?>
<li>
<?php echo ucwords($k);?>
</li>
<?php $i++; } ?>
</ul>
The above code just displayed 30 result from 1500 keyword I have. I want to make Page Numbering navigation also shorting A-Z. So user can Short Keyword by Alphabetic above it and page numbering after it.
Use Datatables.
Table
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>KeyWord</th>
</tr>
</thead>
<tbody>
<?php foreach($kw as $k) { ?>
<tr>
<td><?php echo ucwords($k);?></td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript
$(document).ready(function() {
$('#example').DataTable();
} );
Do include the proper plugin files for js & css. from - Datatables

Need help changing table array by moving a column in PHP

I have been handed the task of making some changes to a PHP webpage that was coded by someone who has left the company and my Php is exactly exeprt.
The page in question displays a database table in a SQL server that allows you to update values via an update page.
Currently the Update function sits under the 'Action' column at the end of the table and I need to relocate the 'Action' column to the start of the table before the 'Name' column.
When I try to make changes, I break the table array and the 'Update' function no longer works.
Current order of columns are;
Name,
Value,
Details,
Action
The new order of columns attempting to achieve
Action,
Name,
Value,
Details
I have also included the code in question.
Any assistance would be appreciated
Note** It is a Php website running on a Windows box and connecting to a MSSQL Server 2008
$query = sqlsrv_query($conn, 'SELECT * FROM Database_Values ORDER BY Name ASC');
// Did the query fail?
if (!$query) {
die( FormatErrors( sqlsrv_errors() ) );
}
// Dump all field names in result
$field_name = "";
foreach (sqlsrv_field_metadata($query) as $fieldMetadata) {
foreach ($fieldMetadata as $name => $value) {
if ($name == "Name") {
$field_name .= $value . '-';
}
}
}
$field_name = substr_replace($field_name, "", -1);
$names = explode("-", $field_name);
?>
<div style="max-height:610px; overflow:auto;">
<table border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" class="table" width="100%">
<tr>
<?php
foreach ($names as $name) {
?>
<th><?php echo $name; ?></th>
<?php
}
?>
<th>Action</th>
</tr>
<?php
// Fetch the row
while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
//print_r($row);
?>
<tr>
<?php
foreach ($row as $key => $eachrow) {
?>
<td nowrap="nowrap">
<?php echo $eachrow; ?>
</td>
<?php
}
?>
<td nowrap="nowrap">
<?php $groupid = $_SESSION["gid"] ;
if($groupid!='1') {
?>
<a href="javascript:void(0);" title="Permission Restricted" >Update</a>
<?php } else { ?>
Update
<?php } ?>
</td>
</tr>
<?php
}
?>
</table>
</div>
All you need to do is change the order of the th and td cells in the html
$query = sqlsrv_query($conn, 'SELECT * FROM Database_Values ORDER BY Name ASC');
// Did the query fail?
if (!$query) {
die( FormatErrors( sqlsrv_errors() ) );
}
// Dump all field names in result
$field_name = "";
foreach (sqlsrv_field_metadata($query) as $fieldMetadata) {
foreach ($fieldMetadata as $name => $value) {
if ($name == "Name") {
$field_name .= $value . '-';
}
}
}
$field_name = substr_replace($field_name, "", -1);
$names = explode("-", $field_name);
?>
<div style="max-height:610px; overflow:auto;">
<table border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" class="table" width="100%">
<tr>
<th>Action</th>
<?php
foreach ($names as $name) {
?>
<th><?php echo $name; ?></th>
<?php
}
?>
</tr>
<?php
// Fetch the row
while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
//print_r($row);
?>
<tr>
<td nowrap="nowrap">
<?php $groupid = $_SESSION["gid"] ;
if($groupid!='1') {
?>
<a href="javascript:void(0);" title="Permission Restricted" >Update</a>
<?php } else { ?>
Update
<?php } ?>
</td>
<?php
foreach ($row as $key => $eachrow) {
?>
<td nowrap="nowrap">
<?php echo $eachrow; ?>
</td>
<?php
}
?>
</tr>
<?php
}
?>
</table>
</div>

Categories