how to create html table in php - php

I have the following snippet of code that basically uses explode to split out these values:
<?php
$data=array();
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line){
$pieces = explode(";", $line);
echo $pieces[0];
echo $pieces[1];
echo $pieces[2];
echo $pieces[3];
//print_r($line);
}
?>
Data: (prod.txt)
PREFIX=abc;PART=null;FILE=/myprojects/school/out/data/feed_abc_2010120810.gz2
PREFIX=efg;PART=sdsu;FILE=mail_efg.dat.2010120810.gz2
Can someone show me how to put this in an HTML table dynamically, like this?? Is there an easy way to do this? Thanks.
PREFIX PART FILE
abc null /myprojects/school/out/data/feed_abc_2010120810.gz2
efg sdsu mail_efg.dat.2010120810.gz2

The Clean Way
<?php
$inputfile = file("prod.txt");
$data_lines = array();
foreach ($inputfile as $line)
{
$data_lines[] = explode(";", $line);
}
//Get column headers.
$first_line = array();
foreach ($data_lines[0] as $dl)
{
$first_line[] = explode("=", $dl);
}
$headers = array();
foreach ($first_line as $fl)
{
$headers[] = $fl[0];
}
// Get row content.
$data_cells = array();
for ($i = 0; $i < count($data_lines); $i++)
{
$data_cell = array();
for ($j = 0; $j < count($headers); $j++)
{
$data_cell[$j] = substr($data_lines[$i][$j], strpos($data_lines[$i][$j], "=")+1);
}
$data_cells[$i] = $data_cell;
unset($data_cell);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTML Table With PHP</title>
</head>
<body>
<table border="1">
<tr>
<?php foreach ($headers as $header): ?>
<th><?php echo $header; ?></th>
<?php endforeach; ?>
</tr>
<?php foreach ($data_cells as $data_cell): ?>
<tr>
<?php for ($k = 0; $k < count($headers); $k++): ?>
<td><?php echo $data_cell[$k]; ?></td>
<?php endfor; ?>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>

This should be flexible enough and won't require any hard-coded pair names:
<?php
$lines = preg_split('~\s*[\r\n]+\s*~', file_get_contents('prod.txt'));
foreach($lines as $i => $line) {
$pairs = explode(';', $line);
foreach($pairs as $pair) {
list($column, $value) = explode('=', $pair, 2);
$columns[$column] = true;
$rows[$i][$column] = $value;
}
}
$columns = array_keys($columns);
echo '<table><thead><tr>';
foreach($columns as $column) {
echo '<th>'.$column.'</th>';
}
echo '</tr></thead><tbody>';
foreach($rows as $row) {
echo '<tr>';
foreach($columns as $column) {
echo '<td>'.$row[$column].'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
?>

echo '<table><tr><td>PREFIX</td><td>Part</td>File</td></tr>';
foreach ($Inputfile as $line){
$pieces = explode(";", $line);
$count=count($pieces);
echo '<tr>';
for ($counter=0; $counter <$count; $counter++)
{
echo '<td>'.$pieces[$counter].'<td>';
}
echo '</tr>';
}

Not the prettiest solution, just an example:
echo '<table><tr><td>PREFIX</td><td>PART</td><td>FILE</td></tr>';
foreach ($Inputfile as $line)
{
$pieces = explode(';', $line);
echo sprintf(
'<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
ltrim($pieces[0], 'PREFIX='),
ltrim($pieces[1], 'PART='),
ltrim($pieces[2], 'FILE=')
);
}
echo '</table>';

You've really got two problems here:
1) Parsing the information in each line into a record / associative array
2) Representing the series of these records/arrays as an HTML table.
Good code will separate these concerns somewhat.
function line2record($line) {
$recordAA = array();
$keyValuePairs = explode(';',$line);
foreach($keyValuePairs as $kvp) {
$pieces = explode('=',$kvp);
$recordAA[$pieces[0]] = $pieces[1];
}
return $recordAA;
}
function record2TR($recordAA) {
$str = implode('</td><td>',$recordAA);
return "<tr><td>$str</td></tr>";
}
After that, it's pretty much a matter of applying these two functions to each line of the file:
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line)
echo record2TR(line2record($line));
To get the header row, and the table/open close markup, you might do something like this:
function record2TH($recordAA) {
$headers = array_keys($recordAA);
$str = implode('</th><th>',$headers);
return "<tr><th>$str</th></tr>";
}
and then:
$fp = fopen('prod.txt','r');
$line = fgets($fp,MAX_LINE_LENGTH); // you'd set this constant
$firstRecord = line2record($line);
echo "<table>";
echo record2TH($firstRecord);
echo record2TR($firstRecord);
while($line = fgets($fp,MAX_LINE_LENGTH))
echo record2TR(line2record($line));
echo "</table>";

This was my approach
echo '<table id="time-table" border="2"><thead><tr >';
echo '<th style="width:40%; padding: 7px;">Course Code</th>';
echo '<th style="width:30%">Course Name</th>';
echo '<th style="width:40%">Slot</th>';
for ($x = 0; $x < 5; $x++) {
echo '<tr id=row'.$x.'>';
echo '<th style="width:40%; padding: 15px;" >',$xml_data->children()[$x]->coursecode .'</th>';
echo '<th style="width:30%">',$xml_data->children()[$x]->coursename .'</th>';
echo '<th style="width:20%">',$xml_data->children()[$x]->slot .'</th>';
}
echo '</tbody></table>';

<?php
class Table
{
private $table;
private $rows;
public function __construct()
{
}
function valueof($var, $key, $default_return_value = null, $run_value_in_this_function = '')
{
$return_value = $default_return_value;
if (is_object($var)) {
if (isset($var->$key)) {
$return_value = trim($var->$key);
}
} elseif (is_array($var)) {
if (isset($var[$key])) {
$value = $var[$key];
$return_value = is_string($value) ? trim($value) : $value;
}
} else {
$return_value = $default_return_value;
}
if (!empty($return_value) && !empty($run_value_in_this_function)) {
if (function_exists($run_value_in_this_function)) {
$return_value = $run_value_in_this_function($return_value);
}
}
return $return_value;
}
function addRow($index)
{
$this->rows[$index] = [];
$this->table['rows'][$index] = [];
}
function addRows($rows)
{
$rows = (int) $rows;
for ($r = 0; $r <= $rows; ++$r) {
$this->rows[$r] = [];
$this->table['rows'][$r] = [];
}
}
function addCell($row_index, $cell_index, $cell_value)
{
$this->table['rows'][$row_index][$cell_index] = $cell_value;
}
function updateCell($row_index, $cell_index, $cell_value)
{
$this->table['rows'][$row_index][$cell_index] = $cell_value;
}
function updateColumn($column_index, $cell_values = [])
{
if (isset($this->table['rows'])) {
if (count($this->table['rows']) > 0) {
foreach ($this->table['rows'] as $row_index => $row_cells) {
$value_index = $row_index;
$new_value = $this->valueof($cell_values, $value_index);
if (!is_null($new_value)) {
$this->updateCell($row_index, $column_index, $new_value);
}
}
}
}
}
function updateRow($row_index, $row_values = [])
{
if (isset($this->table['rows'][$row_index])) {
$columns = count($this->table['rows'][$row_index]);
foreach ($this->table['rows'][$row_index] as $column_index => $column_value) {
$value_index = $column_index-1;
$new_value = $this->valueof($row_values, $value_index);
if (!is_null($new_value)) {
$this->updateCell($row_index, $column_index, $new_value);
}
}
}
}
function addHeader($row_values = [])
{
if (!empty($row_values)) {
$this->updateRow(0, $row_values);
}
}
function addColum($column_index)
{
if (isset($this->table['rows'])) {
if (count($this->table['rows']) > 0) {
foreach ($this->table['rows'] as $row_index => $row_cells) {
$this->table['rows'][$row_index][$column_index] = null;
}
}
}
}
function addColums($columns)
{
$columns = (int) $columns;
for ($col = 1; $col <= $columns; ++$col) {
if (isset($this->table['rows'])) {
if (count($this->table['rows']) > 0) {
foreach ($this->table['rows'] as $row_index => $row_cells) {
$this->table['rows'][$row_index][$col] = null;
}
}
}
}
}
public function getTable()
{
if (isset($this->table['rows']) && is_countable($this->table['rows'])) {
$table = "<table border=\"1\" width=\"50%\">";
foreach ($this->table['rows'] as $row_index => $row_cells) {
$table .= "<tr>";
if (is_countable($row_cells)) {
foreach ($row_cells as $cell_index => $cell_value) {
if (empty($cell_value)) {
$cell_value = ' ';
}
$table .= "<td class=\"data\"> {$cell_value}</td>";
}
}
$table .= "</tr>";
}
$table .= "</table>";
}
return $table;
}
function makeTable()
{
$this->addRows(5);
$this->addColums(4);
$this->addHeader(['No', 'Name', 'Unit', 'Number']);
$this->updateColumn(1, [null, '1', '2', '3', '4', '5' ]);
$this->updateColumn(2, [null, 'Cat', 'Dog', 'Horse', 'Cow', 'Hen']);
$this->updateColumn(3, [null, 'Each', 'Each', 'Each', 'Each' ]);
$this->updateColumn(3, [null, 10,20, 5, 50, 45]);
// echo '<pre>';
// print_r($this->table);
// echo '</pre>';
$table = $this->getTable();
return $table;
}
}
$table = new Table();
print $table->makeTable();

Related

How to insert coordinates of a table into an array in PHP

I am making the game battleships in PHP and I need to make it so that the computer randomly chooses 5 coordinates(x, y), and they have to be in a straight line (column or row). How do I make it so the coordinates are in a line and how do I connect the coordinates to the table cells?
Here's what I have so far:
<?php
session_start();
$i=0;
$start=1;
$st=65;
$l=0;
$polje=array();
$x=(mt_rand(0, 10));
$y=(mt_rand(0, 10));
for($q=0; $q<5; $q++){
$polje[$l]=array($x, $y);
}
echo "<table id='table'>\n";
while ($i<11){
$ascii=chr($st);
echo "<tr>";
for($k=0; $k<11; $k++, $start++){
if($k==0){
echo "<td>$i</td>";
}
else if($i==0){
echo "<td class='td2'>$ascii</td>";
$ascii++;
}
else{
echo "<td class='td1'> </td>";
}
}
echo "</tr>";
$i++;
}
?>
This is what the table looks like:
I like this kind of challenge.
Of course, there is a lot of ways, better ways to do this, with OOP, but you can get the point.
Read the comments through the code and if you have any doubts feel free to ask.
I did some treatment to avoid ships overlapping each other, and random deployment.
const BOARD_SIZE = 10; //10x10 board
const SUBMARINE = 1;
const DESTROYER = 2;
const BATTLESHIP = 3;
const AIRCRAFTCARRIER = 4;
$ships_available = [];
//populate with some data based on game rule
array_push($ships_available, SUBMARINE);
array_push($ships_available, SUBMARINE);
array_push($ships_available, DESTROYER);
array_push($ships_available, DESTROYER);
array_push($ships_available, DESTROYER);
array_push($ships_available, BATTLESHIP);
array_push($ships_available, BATTLESHIP);
array_push($ships_available, AIRCRAFTCARRIER);
$board = [];
while(count($ships_available) > 0) {
deployShip($board, $ships_available);
}
$lastColumnLetter = chr(ord('A')+ BOARD_SIZE-1);
//print table
echo "<table border='1' align='center'>";
echo "<tr><td></td><td>".implode('</td><td>',range(1, BOARD_SIZE))."</td></tr>";
for($i = 'A'; $i <= $lastColumnLetter; $i++) {
echo "<tr><td>".$i."</td>";
for($j=0; $j < BOARD_SIZE; $j++) {
echo "<td align='center'>";
echo $board[$i][$j] ?: ' ';
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
exit;
function array_merge_custom($array1, $array2) {
foreach($array2 as $key => $value) {
foreach($value as $k => $v) {
$array1[$key][$k] = $v;
}
}
return $array1;
}
function deployShip(&$board, &$ships_available) {
$randomShipKey = array_rand($ships_available);
$ship = $ships_available[$randomShipKey];
$beginCoordinates = getRandomCoordinates();
$coordinates = getShipCoordinates($board, $beginCoordinates, $ship);
if(!$coordinates) {
return false;
}
unset($ships_available[$randomShipKey]);
$board = array_merge_custom($board,$coordinates);
}
function getRowNumberByLetter($letter) {
return array_search($letter, range('A','Z'));
}
function getRowLetterByNumber($number) {
$letters = range('A','Z');
return $letters[$number];
}
function getRandomCoordinates() {
return ['row' => chr(mt_rand(ord('A'), (ord('A') + BOARD_SIZE-1))), 'col' => mt_rand(0,BOARD_SIZE -1)];
}
function getShipCoordinates($board, $beginCoordinates, $ship) {
if(isset($board[$beginCoordinates['row']][$beginCoordinates['col']])) {
return false; //anchor position already taken
}
if($ship == 1) {
$return[$beginCoordinates['row']][$beginCoordinates['col']] = 1;
return $return;
}
$shipArraySize = $ship -1;
$directions = ['left', 'right', 'up', 'down'];
$tries = 10;
while($tries > 0) {
$tries--;
$direction = $directions[array_rand($directions)];
$return = [];
switch($direction) {
case 'left':
if(($beginCoordinates['col'] - $shipArraySize) < 0) { //check if can go left
break;
}
for($colBegin = ($beginCoordinates['col'] - $shipArraySize), $colEnd = $beginCoordinates['col']; $colBegin <= $colEnd; $colBegin++) {
if(!empty($board[$beginCoordinates['row']][$colBegin])) {
break 2;
} else {
$return[$beginCoordinates['row']][$colBegin] = $ship;
}
}
return $return;
case 'right':
if(($beginCoordinates['col'] + $shipArraySize) > BOARD_SIZE -1) { //check if can go right
break;
}
for($colBegin = $beginCoordinates['col'], $colEnd = ($beginCoordinates['col'] + $shipArraySize); $colBegin <= $colEnd; $colBegin++) {
if(!empty($board[$beginCoordinates['row']][$colEnd])) {
break 2;
} else {
$return[$beginCoordinates['row']][$colBegin] = $ship;
}
}
return $return;
case 'up':
if((getRowNumberByLetter($beginCoordinates['row']) - $shipArraySize) < 0) { //check if can go up
break;
}
for($rowBegin = (getRowNumberByLetter($beginCoordinates['row']) - $shipArraySize), $rowEnd = getRowNumberByLetter($beginCoordinates['row']); $rowBegin <= $rowEnd; $rowBegin++) {
if(!empty($board[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']])) {
break 2;
} else {
$return[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']] = $ship;
}
}
return $return;
case 'down':
if((getRowNumberByLetter($beginCoordinates['row']) + $shipArraySize) > BOARD_SIZE -1) { //check if can go down
break;
}
for($rowBegin = getRowNumberByLetter($beginCoordinates['row']), $rowEnd = (getRowNumberByLetter($beginCoordinates['row']) + $shipArraySize); $rowBegin <= $rowEnd; $rowBegin++) {
if(!empty($board[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']])) {
break 2;
} else {
$return[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']] = $ship;
}
}
return $return;
}
}
return false;
}

How can i turn these into groups of 4 instep of 2?

So this is my code it takes a list o people from the database and lists them with their partners in groups. Within these groups, the user id of the people cannot appear in the same row twice. Everything works, Im just wondering how to make it echo 4 people per group versus only 2.
if ($result = $mysqli->query("SELECT * FROM performers")) {
printf("Found %d rows.\n", $result->num_rows);
$rows = array();
while ($row = $result->fetch_array()) {
foreach ($row as $key => $col) {
unset($row[$key]);
$row[strtolower($key)] = $col;
}
$rows[] = $row;
}
$current = null;
$count = 1;
while ( ! empty($rows)) {
if ($current) {
$current_performers = array($current['performerid_1'], $current['performerid_2']);
$found = false;
foreach ($rows as $key => $row) {
if ( ! in_array($row['performerid_1'], $current_performers) && ! in_array($row['performerid_2'], $current_performers)) {
$found = $key;
break;
}
}
if ($found !== false) {
echo '<li>', $rows[$found]['performance_id'], ': ', $rows[$found]['perf_name_1'], ' - ', $rows[$found]['perf_name_2'], '</li>';
unset($rows[$key]);
}
else {
echo '';
}
echo '</ul><hr />';
$current = null;
} else {
$current = array_shift($rows);
echo '<h3>Group ', $count+, '</h3>';
echo '<ul>';
echo '<li>', $current['performance_id'], ': ', $current['perf_name_1'], ' - ', $current['perf_name_2'], '</li>';
}
}
I think this should do it, but I haven't tested it (except to verify syntax) because I don't have any sample data.
$group_size = 4;
$current_performers = array();
$current_size = 0;
$count = 1;
while (!empty($rows)) {
if ($current_size == $group_size) { // End previous group
echo '</ul><hr>';
$current_performers = array();
$current_size = 0;
}
if ($current_size == 0) {
echo '<h3>Group ', $count++, '</h3>';
echo '<ul>';
}
$found = false;
foreach ($rows as $key => $row) {
if ( ! in_array($row['performerid_1'], $current_performers) && ! in_array($row['performerid_2'], $current_performers)) {
$found = true;
array_push($current_performers, $row['performerid_1'], $row['performerid_2']);
$current_size++;
echo '<li>', $row['performance_id'], ': ', $row['perf_name_1'], ' - ', $row['perf_name_2'], '</li>';
unset($rows[$key]);
break;
}
}
if (!$found) {
// Force a new group to start
$current_size = $group_size;
}
// If we have an unfinished group, finish it
if ($current_size) {
echo '</ul><hr>';
}
}

Code help, Unlimited php menu

Just got this code working for 2 levels of my menu. But I want it to work with unlimited levels.
Do any of you guys have an idea where to start?
Right now if I type in more levels in the database it says "Undefined index Linnk & Label Line 29", and the new parent that has been entered does not show up.
$sql = "SELECT id, label, link_url, parent_id FROM dyn_menu ORDER BY parent_id, id ASC";
$items = mysql_query($sql);
while ($obj = mysql_fetch_object($items)) {
if ($obj->parent_id == 0) {
$parent_menu[$obj->id]['label'] = $obj->label;
$parent_menu[$obj->id]['link'] = $obj->link_url;
} else {
$sub_menu[$obj->id]['parent'] = $obj->parent_id;
$sub_menu[$obj->id]['label'] = $obj->label;
$sub_menu[$obj->id]['link'] = $obj->link_url;
if (!isset($parent_menu[$obj->parent_id]['count'])) {
$parent_menu[$obj->parent_id]['count'] = 0;
}
$parent_menu[$obj->parent_id]['count']++;
}
}
mysql_free_result($items);
function dyn_menu($parent_array, $sub_array, $qs_val = "menu", $main_id = "nav", $sub_id = "subnav", $extra_style = "foldout") {
$menu = "<ul id=\"".$main_id."\">\n";
foreach ($parent_array as $pkey => $pval) {
if (!empty($pval['count'])) {
$menu .= " <li><a class=\"".$extra_style."\" href=\"".$pval['link']."?".$qs_val."=".$pkey."\">".$pval['label']."</a></li>\n";
} else {
$menu .= " <li>".$pval['label']."</li>\n";
}
if (!empty($_REQUEST[$qs_val])) {
$menu .= "<ul id=\"".$sub_id."\">\n";
foreach ($sub_array as $sval) {
if ($pkey == $_REQUEST[$qs_val] && $pkey == $sval['parent']) {
$menu .= "<li>".$sval['label']."</li>\n";
}
}
$menu .= "</ul>\n";
}
}
$menu .= "</ul>\n";
return $menu;
}
function rebuild_link($link, $parent_var, $parent_val) {
$link_parts = explode("?", $link);
$base_var = "?".$parent_var."=".$parent_val;
if (!empty($link_parts[1])) {
$link_parts[1] = str_replace("&", "##", $link_parts[1]);
$parts = explode("##", $link_parts[1]);
$newParts = array();
foreach ($parts as $val) {
$val_parts = explode("=", $val);
if ($val_parts[0] != $parent_var) {
array_push($newParts, $val);
}
}
if (count($newParts) != 0) {
$qs = "&".implode("&", $newParts);
}
return $link_parts[0].$base_var.$qs;
} else {
return $link_parts[0].$base_var;
}
}
echo dyn_menu($parent_menu, $sub_menu, "menu", "nav", "subnav");
In order to do this, you'll want to use a recursive function to handle your array -> list transformation.
Here's an example:
<?php
function arrToUl($arr) {
$out = '<ul>';
foreach($arr as $key=>$val) {
$out .= '<li>';
$out .= is_array($val) ? arrToUl($val) : $val;
$out .= '</li>';
}
return $out . '</ul>';
}
$arr = array('firstval','secondval',array('firstval2','secondval2',array('firstval3','secondval3',array('firstval4','secondval4',array('firstval5','secondval5')))));
echo arrToUl($arr);
Output in a jsfiddle.

need help with php loop logic

This code works perfectly except that it doesn't print the last 2 rows of my csv file:
This is the file:
603629,0,ATLV0008,"Vendor1",1942.60,11/04/2010,1942.60,9/1-9/30/10,EFT-JP
603627,2,ATLV0008,"Vendor1",1242.40,11/04/2010,1242.40,7/1-7/31/10,EFT-JP
600023,0,FLD4V0003,"Vendor2",1950.00,06/15/2010,1950.00,6/14/10 Request,EFT-JP
600024,0,FLD4V0003,"Vendor2",1800.00,06/15/2010,1800.00,6/14/10 Request,EFT-JP
603631,0,ATLV5066,"Vendor2",1000.00,11/09/2010,1000.00,11/4/10 Check Request,PM2
603647,0,ATLV5027,"DVendor3",2799.80,11/15/2010,2799.80,10/1-10/31/10 Bishop,PM2
603642,5,ATLV5027,"Vendor3",482.40,11/15/2010,482.40,10/1-10/18/10 Allen,PM2
603653,0,ATLV0403,"Vendor4",931.21,11/17/2010,931.21,9/1-9/30/10,EFT-JP
603661,0,ATLV0105,"Vendor5",26.75,11/19/2010,26.75,093139,PM2
603660,1,ATLV0105,"Vendor5",5.35,11/19/2010,5.35,093472,PM2
Here is the code: (It needs to display the sum of 2 rows with the same vendor before the actual rows)
if (($handle = fopen('upload/ATLANTA.csv', "r")) !== FALSE) {
while (($row_array = fgetcsv($handle, 1000, ","))) {
foreach ($row_array as $key => $val) {
$row_array[$key] = trim(str_replace('"', '', $val));
ob_flush();
}
$complete[] = $row_array;
ob_flush();
}
}
flush();
$prevVendor = '';
$sum = 0;
$venData = '';
if (isset($complete)) {
foreach ($complete as $key => $val) {
$venData .= "<br/>";
$currVendor = $complete[$key][3];
if ($currVendor != $prevVendor){
if ($prevVendor != NULL){
print "<br/>";
print $sum . "<br/>";
print $venData;
$sum = 0; $venData = '';
}
}
foreach ($val as $ikey => $ival){
if ($ikey != 1){
$venData .= $ival . '&nbsp';
$prevVendor = $val[3];
}
}
if ($currVendor == $prevVendor){
$sum += $complete[$key][6];
}
}
}
I don't really understand your problem but if you want to get (and save it wherever you want) the sum of each vendors, you should do something like this :
$prevVendor = null;
$venData = '';
$sums = array();
if (isset($complete) && is_array($complete)) {
$lim = count($complete);
for ($key=0;$key<$lim;++$key) { // no need foreach for simple array
$venData .= "<br/>";
$currVendor = $complete[$key][3];
if ($currVendor != $prevVendor){
if ($prevVendor != null){
print "<br/>";
print $venData;
}
$venData = '';
$prevVendor = $currVendor;
$sums[$currVendor] = 0; // set the counter to 0
}
foreach ($complete[$key] as $ikey => $ival){
if ($ikey != 1){
$venData .= $ival . ' '; // is useful for you I guess
}
}
$sums[$currVendor] += $complete[$key][6]; // add amounts
}
}
if ($prevVendor != null){ // you need to do this to display the last record
print "<br/>";
print $venData;
}
var_export($sums); // check results
This can be some syntax errors ...

PHP - Detect change on string

I have an array which i do a foreach($array as $key => $value)
in my $key i get
name[1][1]
name[1][2]
name[1][3]
name[2][1]
name[2][2]
how can I add detect when the first index changes from [1][3]->[2][1]
any help is appreciated.
What i want to achieve is this:
<h4>Header</h4>
name[1][1]
name[1][2]
name[1][3]
<h4>Header</h4>
name[2][1]
name[2][2]
<h4>Header</h4>
name[3][1]
name[3][2]
name[3][3]
name[3][4]
Don't know if it is the best option, but this is how i managed to do it.
<?php $k = 1; $flag1 = 0; $flag2 = 1;foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>
<?php
$endpos = strpos($option_name,']');
$asd = substr($option_name,5,$endpos-5);
$this->firephp->log($asd);
if($asd % 2)
{
if($flag1 === 0)
{
echo ' <h4>Header '. $k .'</h4>';
$flag1 = 1;
$flag2 = 0;
$k++;
}
}
else
{
if($flag2 === 0)
{
echo ' <h4>Header '. $k. '</h4>';
$flag2 = 1;
$flag1 = 0;
$k++;
}
}
?>
You can try like
foreach($name as $parent_key => $parent_value){
echo "<h4>Header</h4><br/>";
foreach($name[$parent_key] as $key=>$value)
{
echo $name[$i][$key]."<br/>";
}
}
foreach($array as $key => $value){
$valuevalues = array();
foreach($value as $val){
if($val != "" && !isset($valuevalues[$key][$val]))
$valuevalues[$key][$val] = "different-than-previous";
if(!isset($valuevalues[$key][$val]))
$valuevalues[$key][$val] = "equal-to-first-value";
}
}

Categories