how to Merge two cell on one cell - php

i have tow row that have the same data but only one cell Different than other like this :-
Customer Name | No Room | Room Type
Maikle dived 2 single
Maikle dived 1 double
So i wont to merge the Customer on one cell like this :-
Customer Name | No Room | Room Type
2 single
Maikle dived
1 double
how can i do this by PHP and mysql

If you are trying to output it as HTML then do following:
//$source should hold the data from DB
$source = array(
array('Maikle dived' => array('No Room' => 2, 'Room Type' => 'single'),
array('Maikle dived' => array('No Room' => 1, 'Room Type' => 'double'),
);
$result = array();
foreach($source as $item) {
$user = key($item);
$val = current($item);
if(!isset($result[$user])) {
$result[$val] = array();
}
$result[$user][] = $val;
}
then you can loop through the $result to build html
foreach($result as $user => $vals) {
echo $user;
echo '<ul>';
foreach($vals as $val) {
echo '<li>'.$val.'</li>';
}
echo '</ul>';
}

Related

php dynamic table from muldimentional array

can you give me idea how to implement this idea for "dynamic" html table.
I have an array
$arr = array(
array(
'label' => 'First name',
'data' => array(
array('fname' => 'John'),
array('fname' => 'Ralph'),
),
),
array(
'label' => 'Last name',
'data' => array(
array('lname' => 'Doe'),
array('lname' => 'Loren'),
),
),
array(
'label' => 'Description',
'data' => array(
array('description' => 'Something bout John'),
array('description' => 'Something about Ralph'),
),
),
);
Now from the keys 'label' im creating the table columns
---------------------------------------
|First Name | Last Name | Description |
---------------------------------------
The problem is how to put 'fname' keys in the first column, 'lname' in the second and 'description' in the third.
With this part of code im trying to put the data in all columns
private function tableBody()
{
$data = $this->data;
$table = '<tbody>';
foreach($data as $key => $value){
foreach($value['data'] as $k => $v){
$table .= '<tr>';
foreach($v as $col => $name){
$table .= '<td>' . $name . '</td>';
}
$table .= '</tr>';
}
}
$table .= '</tbody>';
return $table;
}
Also my idea is not to hard code array keys for multiple usage(except label and data).
First I would remap the data to process it in loops.
$labels = [];
$rows = [];
foreach($arr as $column) {
$label = $column['label'];
$labels[] = $label;
foreach($column['data'] as $key => $value) {
$rows[$label][] = $value;
}
}
Now print out the labels with the headline.
echo "<table>\n";
echo "<tr>";
foreach($labels as $label) echo "<th>{$label}</th>";
echo "</tr>\n";
Iterate through the rows and create the HTML.
$labelCount = count($labels);
$rowCount = count($rows[$labels[0]]);
while($rowCount) {
echo "<tr>";
for ($i = 0; $i < $labelCount; $i++) {
$current = array_shift($rows[$labels[$i]]);
$value = reset($current);
echo "<td>{$value}</td>";
}
echo "</tr>\n";
$rowCount--;
}
echo "</table>\n";
This gives a table like below
<table>
<tr><th>First name</th><th>Last name</th><th>Description</th></tr>
<tr><td>John</td><td>Doe</td><td>Something bout John</td></tr>
<tr><td>Ralph</td><td>Loren</td><td>Something about Ralph</td></tr>
</table>
You need to manipulate the initial array to reduce it to something more manageable. You could brute force your way like so:
function reduce($data) {
$ret = [];
foreach ($data as $d1) {
// column header could have been fetched here
foreach ($d1 as $k2 => $d2) {
// keeping track of what label we need
$key = '';
// keeping the values together
$child = [];
// discarding non arrays
if (is_array($d2)) {
foreach ($d2 as $d3) {
// identifier fetch from this level
foreach ($d3 as $k4 => $d4) {
$key = $k4;
$child[] = $d4;
}
}
}
// assigning back to the main array only if we have something
if (!empty($child)) {
$ret[$key] = $child;
}
}
}
return $ret;
}
That will return the following:
Array
(
[fname] => Array
(
[0] => John
[1] => Ralph
)
[lname] => Array
(
[0] => Doe
[1] => Loren
)
[description] => Array
(
[0] => Something bout John
[1] => Something about Ralph
)
)

Print same rows as once in php while loop

I have three colums which has same values for two of the rows. I want to print only one of a same row out of the two same rows using a php while loop statement. This is how the data is
ID values
1 MINI
1 MINI
2 MINI
I want to print all of these but only once with same rows based on the ID
ID Values
1 MINI
2 MINI
I can actually use DISTINCT OR GROUP BY in mysql query to find the expected answer above but I really need to use a php while statement.
This is what I have been trying my hands on
$query="SELECT * from table";
$sR=$db->query($query);
$array=array();
while($sRow=mysqli_fetch_assoc($sR)){
$ID=$searchRow['ID'];
$values=$searchRow['Values'];
$array[$ID][]=$ID;
$array2[$ID][]=$values;
}
foreach($array as $ID => $item){
$value=$array[$ID];
foreach($item as $newItem){
if($newItem===$newItem){
echo '---'.$newItem;
break;
}
}
}
This is what I am trying hands on but it doesn't seem to work as expected, I would need help on it. Thanks soo much.
When I do things like this I use a "Previous ID"-variable, in this case $PRID, to check if the ID is a duplicate. The SQL query has to be ordered by ID to make this work.
$query="SELECT * FROM table ORDER BY ID";
$sR=$db->query($query);
$array=array();
$PRID=0;
while($sRow=mysqli_fetch_assoc($sR)){
$ID=$searchRow['ID'];
$values=$searchRow['Values'];
if($ID>$PRID){
$array[$ID][]=$ID;
$array2[$ID][]=$values;
}
$PRID=$ID;
}
foreach($array as $ID => $item){
$value=$array[$ID];
foreach($item as $newItem){
if($newItem===$newItem){
echo '---'.$newItem;
break;
}
}
}
just try option 1 or option 2
$query="SELECT * FROM table ORDER BY ID";
$sR=$db->query($query);
$array = array();
// first option, expected output
// array(
// 0 => 'value',
// 1 => 'value'
// )
foreach($sR as $value) {
$array[$value['ID']] = $value['Values'];
}
var_dump($array);
$array2 = array();
// second option
foreach($sR as $value) {
$array2[$value['ID']] = array(
'ID' => $value['ID'],
'Value' => $value['Value']
);
}
var_dump($array2);
// expected output
// array(
// 0 => array(
// 'ID' => 0,
// 'Value' => 'value'
// ),
// 1 => array(
// 'ID' => 1,
// 'Value' => 'value'
// )
// )

PHP: how to process this data from database

I'm pretty new to programming so I'm sorry if this is very nooby.
In a dummy database I have a column called currencies. The column has this data:
36:USD,74:GBP,68:USD,119:USD,114:BGN,15:USD,32:GBP,1:BGN
Above data is the amount and its respective currency the user has paid.
What I want to do is to display a table with each currency and the total amount of sales for that country and also display it in table form.
So with the above data, I want the output below:
Currency | # Sales
____________________
USD 4
GPB 2
BGN 2
____________________
Total: 8
Try this
$data = "36:USD,74:GBP,68:USD,119:USD,114:BGN,15:USD,32:GBP,1:BGN";
$data = explode(",", $data);
$result = array();
foreach ($data as $value) {
$d_array = explode(":", $value);
if(isset($result[$d_array[1]]))
$result[$d_array[1]] +=1;
else
$result[$d_array[1]] = 1;
}
$total = count($data);
var_dump($result);
var_dump($total);
And the result
array (size=3)
'USD' => int 4
'GBP' => int 2
'BGN' => int 2
int 8
$data = "36:USD,74:GBP,68:USD,119:USD,114:BGN,15:USD,32:GBP,1:BGN";
$data = explode(",", $data);
$final_array = array();
foreach ($data as $value)
{
$new_array = explode(":", $value);
array_push($final_array, $new_array[1]);
}
$final_array = array_count_values($final_array);
print_r($final_array);
Result
Array ( [USD] => 4 [GBP] => 2 [BGN] => 2 )
Take a look at my example. I hope its fine for you.
$orders = array("36:USD","74:GBP","68:USD","119:USD","114:BGN","15:USD","32:GBP","1:BGN");
$totalData = array();
foreach($orders as $singleOrder) {
$explodedData = explode(':',$singleOrder);
if(!isset($totalData[$explodedData[1]])) {
$totalData[$explodedData[1]] = $explodedData[0];
} else {
$totalData[$explodedData[1]] += $explodedData[0];
}
}
var_dump($totalData);
result
array (size=3)
'USD' => int 238
'GBP' => int 106
'BGN' => int 115

PHP: Accessing multidimensional array with foreach and outputting the results as table

I've been stuck on this coding for quite some time now. I'm new to PHP, so I might've made a stupid mistake somewhere. My aim is to show a table of attendance for a month after a user selects the date and year. Similar to this
January 2015
Name |1 |2 |3|...|31|
STAFF A-Full Name |9:02|8:30| |...| |
STAFF B-Full Name |8:43| | |...| |
This is the code I'm talking about:
<html>
<?php
error_reporting(0);
//database connection goes here
$m = $_POST['month'];
$y = $_POST['year'];
$inidate= print_r($y.'/'.$m.'/%',true);
$sql = "SELECT NAME, DATEIN, TIMEIN FROM VXDTIME WHERE NAME != '' AND NAME LIKE '%-%' AND NAME NOT LIKE '%Old% %Data%' AND TIMEIN != '' ORDER BY NAME, DATEIN";
$result = ibase_query($connect,$sql);
$staff = $dome = array();
$getmonth = date("m",strtotime($inidate));
$getyear = date("Y",strtotime($inidate));
while($row = ibase_fetch_assoc($result))
{ $dome[] = $row; }
foreach($dome as &$value)
{
if (ctype_upper(substr($value['NAME'],0,2))== TRUE)
$staff = $value['NAME'];
}
$staff = array_values(array_unique($staff,SORT_REGULAR));
//***************************
foreach ($staff as $key1 => $value1)
{
foreach ($dome as $key => $value)
{
for ($i=0;$i<cal_days_in_month(CAL_GREGORIAN,$getmonth,$getyear);$i++)
{
if ($value1 == $key['NAME']) //compares name
if ($key['DATEIN'] != NULL) //compares date
if (idate("d",strtotime($key['DATEIN'])) == (i+1))
$key1[$i+1] = $key['TIMEIN'];
else
$key1[$i+1] = 'No Record';
else
$key1[$i+1] = 'Blank';
}
}
}
//Make the array start at 0
//$staff = array_values($staff);
//array_walk($staff, create_function('&$v,$k', 'if (is_array($v)) $v=array_values($v);'));
$getdate = print_r($y.'/'.$m.'/01',true);
echo "<table border=1><tr><td>No.</td> <td style='width:350'>Name</td>";
for($i=0;$i<cal_days_in_month(CAL_GREGORIAN,$getmonth,$getyear);$i++)
echo "<td style='width:40'>".($i+1)."</td>";
echo "</tr>";
$count=0;
foreach ($staff as $key => $value)
{
echo "<tr><td>".($count+1)."</td><td>".$key[0]."</td>";
for($j=1;$j<(cal_days_in_month(CAL_GREGORIAN,$getmonth,$getyear)+1);$j++)
{
if (date("D",strtotime($getdate)) == 'Sat' || date("D",strtotime($getdate)) == 'Sun')
echo "<td BGCOLOR='#525266'> </td>";
else
if (strtotime($key[$j]) > strtotime('09:10'))
echo "<td BGCOLOR='#ffff00'>".$key[$j]."</td>";
else
echo "<td>".$key[$j]."</td>";
}
echo "</tr>";
$getdate=strftime("%Y/%m/%d", strtotime("$getdate +1 day"));
count++;
}
echo "</table>";
?>
</html>
var_dump($dome) looks like this
array
0 =>
array
'NAME' => string 'STAFF A-Full Name'
'DATEIN' => string '2015/01/01' //string date/time isn't not my choice
'TIMEIN' => string '09:02'
1 =>
array
'NAME' => string 'STAFF A-Full Name'
'DATEIN' => string '2015/01/02'
'TIMEIN' => string '08:30'
2 =>
array
'NAME' => string 'STAFF B-Full Name'
'DATEIN' => string '2015/01/01'
'TIMEIN' => string '08:43'
3 =>
array
'NAME' => string 'Staff B-Full Name'
'DATEIN' => string '2012/01/01'
'TIMEIN' => string '09:11'
//and so on...
Despite reading many guides here about accessing multidimensional array, I still can't understand how to use foreach, using keys and such. I'm sure this code looks really messy but right now I'm stumped.
I hope someone can help me.
EDIT: Found the solution to the the duplicate problem
Another problem I'm having is that I'm not sure my way of accessing the array is correct. By the end of the code, $staff should look like this:
array
0 =>
array
'NAME' => string 'STAFF A-Full Name'
0 => string '09:02'
1 => string '08:30'
2 => string '09:00'
//... all the way to the end of month
1 =>
array
'NAME' => string 'STAFF B-Full Name'
0 => string '08:43'
1 => string '09:01'
2 => string '08:50'
//...
//...
I'll need to loop through $staff and $dome in order to extract the time from the latter into the former. But I'm not sure I'm doing the foreach correctly to achieve that.
Apologies, editing as I read your code wrong.
It looks like you are assigning a value to the variable $staff, instead of stuffing that value into the existing array at $staff.
foreach($dome as &$value)
{
$staff = $value['NAME'];
}
$staff = array_unique($staff);
should be:
foreach($dome as &$value)
{
$staff[] = $value['NAME'];
}
$staff = array_unique($staff);

How to merge table row with PHP array?

I want to merge the table row if the date have an same id's. I have some array data like this :
Array
(
[0] => Array
(
[id] => 2
[date] => 05/13/2014
[content] => some contents 1
[act] => act1 act2 act3
)
[1] => Array
(
[id] => 2
[date] => 05/28/2014
[content] => some contents 1
[act] => act1 act2 act3
)
[2] => Array
(
[id] => 7
[date] => 06/04/2014
[content] => some contents 2
[act] => act1 act2 act3
)
)
Then I tried to group its data into the same id by :
if($queryx = $this->mymodel->myfunction($par)){
$datax = $queryx;
}
$i = 0;
foreach ($datax as $idx => $val) {
$dates[$val['id']][$i] = $val['date'].",".$val['id'];
$contn[$val['id']][$i] = $val['content'];
$i++;
}
then :
$j = 0; $y = 0;
echo "<table border='1'>\r\n";
foreach ($dates as $idx => $val) {
$tmpexp = explode(',', $val[$j]);
echo "<tr>\r\n";
echo "<td rowspan='".count($val)."'>".$tmpexp[0]."</td>\r\n";
foreach ($val as $idx1 => $val1) {
if($idx1 > 0)
{
echo "<tr>\r\n";
}
echo "<td>".$dates[$tmpexp[1]][$y]."</td>\r\n";
if($idx1 < 1)
{
echo "<td rowspan='".count($val)."'>".$contn[$tmpexp[1]][$y]."</td>\r\n";
echo "<td rowspan='".count($val)."'>act1 act2 act3</td>";
echo "</tr>\r\n";
}
$y++;
}
$j++;
}
echo "</table>";
There is no problem if the data have at least two child, but if the date only have one child (see data with id's 7) there is show an error because Undefined offset. So how I add some handler if there is only one child on the data. There is my desired result:
Please see this image:
I use the 'read ahead' technique for processing nested loops. It does mean that 'foreach' loops cannot be used as the next record must be read as soon as the current one has been processed. Basically, the last action you do in the loop is read the next record as you are setting it up for the next iteration. Note, you never test when to print a record as that is decided by the structure of the groups. The code loops are the same as the structure of the groups in the data
A 'group' is all the records with the same id.
I assume that the 'content' and 'act' are identical for each entry in the group.
Edited to add 'rowspan' attributes to the appropriate 'td' tags. I suspect css may be easier at this point.
The issue is that the group cannot be displayed until it is known how many entries are in it.
So, i 'buffer' all the records belonging to a group in an array. at the end of the group, it is displayed with the appropriate 'rowspan' attributes in the html.
It is tested on PHP 5.3.18. It includes test data.
<?php /* Q24028866 */
$testData = array(array('id' => 2, 'date' => '05/13/2014', 'content' => 'some contents 2', 'act' => 'act1 act2 act3'),
array('id' => 2, 'date' => '05/28/2014', 'content' => 'some contents 2', 'act' => 'act1 act2 act3'),
array('id' => 7, 'date' => '06/04/2014', 'content' => 'some contents 7', 'act' => 'act1 act2 act3'),
array('id' => 8, 'date' => '06/08/2014', 'content' => 'some contents 8', 'act' => 'act1 act2 act3'),
array('id' => 8, 'date' => '06/09/2014', 'content' => 'some contents 8', 'act' => 'act1 act2 act3'));
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table border='1'>
<thead><th>Date</th><th>Content</th><th>Act</th></thead>
<?php
// use 'read ahead' so there is always a 'previous' record to compare against...
$iterContents = new \ArrayIterator($testData);
$curEntry = $iterContents->current();
while ($iterContents->valid()) { // there are entries to process
$curId = $curEntry['id'];
// buffer the group to find out how many entries it has...
$buffer = array();
$buffer[] = $curEntry;
$iterContents->next(); // next entry - may be same or different id...
$curEntry = $iterContents->current();
while ($iterContents->valid() && $curEntry['id'] == $curId) { // process the group...
$buffer[] = $curEntry; // store all records for a group in the buffer
$iterContents->next(); // next entry - may be same or different id...
$curEntry = $iterContents->current();
}
// display the current group in the buffer...
echo '<tr>';
echo '<td>', $buffer[0]['date'], '</td>';
$rowspan = count($buffer) > 1 ? ' rowspan="'. count($buffer) .'"' : '';
echo '<td', $rowspan, '>', $buffer[0]['content'], '</td>',
'<td', $rowspan, '>', $buffer[0]['act'], '</td>';
echo '</tr>';
for($i = 1; $i < count($buffer); $i++) {
echo '<tr><td>', $buffer[$i]['date'], '</td>';
echo '</tr>';
}
} ?>
</table>
</body>
</html>
The following code will give you a clue what you should do,
$newArray = array();
$counter=0;
foreach($datax as $key=>$val){
$newArray[$val['id']][$counter]['date'] = $val['date'];
$newArray[$val['id']][$counter]['content'] = $val['content'];
$newArray[$val['id']][$counter]['act'] = $val['act'];
$counter++;
}
$newArray = array_map('array_values', $newArray);

Categories