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

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>';
}
}

Related

How can I add format_number to my code

I am trying to display a number that has the english comma separation.
This code gets the number of likes from multiple pages and displays them in a list ordered by number of facebook likes.
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
function getLikes($arr){
$urls = "";
// Add urls to check for likes
for($i = 0;$i < count($arr);$i++) {
if($urls != "") $urls .= ",";
$urls .= $arr[$i];
}
// Retreive info from Facebook
$xml = simplexml_load_file("http://api.facebook.com/restserver.php?method=links.getStats&urls=" . $urls);
$likes = array();
// Loop through the result and populate an array with the likes
for ($i = 0;$i < count($arr);$i++) {
$url = $xml->link_stat[$i]->url;
$counts = (int)$xml->link_stat[$i]->like_count;
$likes[] = array('likes' => $counts,'url' => $url);
}
return $likes;
}
$array = array("URL HERE","URL HERE");
$likes = getLikes($array);
$likes = array_sort($likes, 'likes', SORT_DESC);
$english_format_number = number_format($likes, 'likes');
foreach ($likes as $key => $val) {
echo "<li class='facebook'><div class='fb-page'><div class='rank'>" . $key . "</div>" . "<div class='thumb " . $val['url'] . "'><div class='link'>" . $val['url'] . "</div></div>" . "<div class='likes'>" . $val['likes'] . "</div></div></li><br />";
}
The code works fine, by the way I am not a coder, and am only just getting into it.
I was trying to add in something like
$english_format_number = number_format($likes, 'likes');
But of course I have no idea if I can do that or where to put it.
Can anyone help?
you use wrong parameter in number_format function. the correct format is number_format(number,decimals,decimalpoint,separator). so change you code to
$english_format_number = number_format($likes, 0, ',', '.') . 'likes';

How to shuffle an array and then slice it

I have a problem with shuffling and slicing array.
I have this code:
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$selectedProducts = array_slice($selectedProducts, 0, $maxDisplayItem);
foreach ($selectedProducts as $_id) {
shuffle($products);
foreach ($products as $_product) {
....
}
}
My code limiting the number of displayed item but didn't shuffle it at all.
When I change the order of actions:
shuffle($selectedProducts);
foreach ($selectedProducts as $_id) {
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$products = array_slice($products, 0, $maxDisplayItem);
foreach ($products as $_product) {
....
}
}
the code shuffling and slicing results but only first (e.g. 3 results) from whole array who has 50 items.
Could anyone help me with this?
here is the whole function:
function displayProductList()
{
// Store View
$store = $this->getStoreViewCode();
$selectedProducts = $this->getSelectedProducts();
$products = $this->_products->getProductsFromDb($selectedProducts, $store, $this->getProductsStoragePid());
// Load Template File
$templateHtml = $this->cObj->fileResource( $this->_getConfig('templateProductList') );
$productListHtml = $this->cObj->getSubpart($templateHtml, '###PRODUCT_LIST###');
$productHtml = $this->cObj->getSubpart($productListHtml, '###PRODUCT_ITEM###');
$subPartContent = ''; $item = 0; $items = count($products); $even = true; $line = '';
shuffle($selectedProducts);
foreach ($selectedProducts as $_id) {
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$products = array_slice($products, 0, $maxDisplayItem);
foreach ($products as $_product) {
if ($_id === $_product['product_id']) {
$markers = $this->_products->getProductMarkers($_product);
// Even/Odd CSS Class Determination
if ($even === true) {
$line = 'even';
$even = false;
} else {
$line = 'odd';
$even = true;
}
// Class Determination First/Last
if ($item == 0) {
$markers['###EVENODD###'] = $line . ' ' . 'first';
} else if ($item == $items-1) {
$markers['###EVENODD###'] = $line . ' ' . 'last';
} else {
$markers['###EVENODD###'] = $line;
}
// Check if the product has an image
$imageHtml = '<p>'.$this->pi_getLL('template_label_no_image_available').'</p>';
if ($markers['###DETAIL_IMAGE###'] != 'no_selection') {
$imageHtml = $this->cObj->getSubpart($productHtml, '###PRODUCT_IMAGE###');
}
$p = $this->cObj->substituteSubpart($productHtml, '###PRODUCT_IMAGE###', $imageHtml);
$subPartContent .= $this->cObj->substituteMarkerArray($p, $markers);
$item++;
}
}
}
return $this->cObj->substituteSubpart($productListHtml, '###PRODUCT_ITEM###', $subPartContent);
}
function displayProductList(){
// Store View
$store = $this->getStoreViewCode();
$selectedProducts = $this->getSelectedProducts();
$products = $this->_products->getProductsFromDb($selectedProducts, $store, $this->getProductsStoragePid());
// Load Template File
$templateHtml = $this->cObj->fileResource( $this->_getConfig('templateProductList') );
$productListHtml = $this->cObj->getSubpart($templateHtml, '###PRODUCT_LIST###');
$productHtml = $this->cObj->getSubpart($productListHtml, '###PRODUCT_ITEM###');
$subPartContent = ''; $item = 0; $items = count($products); $even = true; $line = '';
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$products = array_slice($products, 0, $maxDisplayItem);
shuffle($products);
foreach ($products as $_product) {
$markers = $this->_products->getProductMarkers($_product);
// Even/Odd CSS Class Determination
if ($even === true) {
$line = 'even';
$even = false;
} else {
$line = 'odd';
$even = true;
}
// Class Determination First/Last
if ($item == 0) {
$markers['###EVENODD###'] = $line . ' ' . 'first';
} else if ($item == $items-1) {
$markers['###EVENODD###'] = $line . ' ' . 'last';
} else {
$markers['###EVENODD###'] = $line;
}
// Check if the product has an image
$imageHtml = '<p>'.$this->pi_getLL('template_label_no_image_available').'</p>';
if ($markers['###DETAIL_IMAGE###'] != 'no_selection') {
$imageHtml = $this->cObj->getSubpart($productHtml, '###PRODUCT_IMAGE###');
}
$p = $this->cObj->substituteSubpart($productHtml, '###PRODUCT_IMAGE###', $imageHtml);
$subPartContent .= $this->cObj->substituteMarkerArray($p, $markers);
$item++;
}
return $this->cObj->substituteSubpart($productListHtml, '###PRODUCT_ITEM###', $subPartContent);
}

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