I have the following code:
if(hasRows($resultC)){
while($row = mysql_fetch_row($resultC)) {
$mescategories = '<span><a href="' . CalRoot .
'/index.php?com=searchresult&t=' . $row[0] .
'" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span> | ' ;
echo $mescategories;
}//end while
}//end if
The rendered output looks like:
cat 1 | cat 2 | cat 3 | cat 4 |
How do I prevent the last | character being rendered.
$catArray = array();
if(hasRows($resultC)){
while($row = mysql_fetch_row($resultC)){
array_push($catArray, '<span>' . cOut($row[1]) . '</span>');
}//end while
echo implode('|', $catArray);
}//end if
You could count the number of rows using mysql_num_rows($resultC), and have a counter on your loop. Alternatively, the way I'd do it is something like:
if(hasRows($resultC)){
// Create an empty array
$links = array( );
while($row = mysql_fetch_row($resultC)){
// Add each text link to the array
$links[] = '<span>' . cOut($row[1]) . '</span>' ;
}
// "Glue" the array back together using implode, with the separator between each.
echo implode(' | ', $links );
}
How about putting in a conditional statement. Count the size of the row and if $count=$maxcount then don't echo the "|" character.
$i = 0; //set before while loop
$i++; //inserted into while loop
if ($i != mysql_num_rows($resultC) ) { //inserted into while loop
$mescategories .= " | " ;
}
mysql_num_rows will tell how many rows there are in the query, and then will append the pipe character for each row except the last one.
EDIT: I think the $i++ should come before the if statement, actually.
I have not checked your formatting. Just added a "first" variable.
if(hasRows($resultC)){
$first = true;
while($row = mysql_fetch_row($resultC)){
$mescategories = ' '.($first ? "":"|").' <span>' . cOut($row[1]) . '</span> ' ;
echo $mescategories;
$first = false;
}//end while
}//end if
try
if(hasRows($resultC)){
$i=0;
while($row = mysql_fetch_row($resultC)){
$spaceline =($i>0) ? '|' : '';
$mescategories = '<span>' . cOut($row[1]) . '</span>' ;
$i++;
echo $spaceline.$mescategories;
}//end while
}//end if
Just do
echo substr($mescategories, 0, -1);
instead of echo $mescategories
you let it put | after every instance and then delete the last char
else if you need to know the last key of an array you use:
end($array);
$lastKey = key($array);
but don't forget to reset before you do things with it
reset($array);
Related
I have a problem.
I created a function that returns a output.
My problem is how to return two outputs on one page. Inside a function i have two db_query. The first one gives me teacher information
$temp = '';
foreach($result as $item) {
$temp .= '<b>About teacher | </b>'. $item->title .' '. $item->name .' '. $item->lname .' , ' . $item->xyz .' <br />';
$temp .= '<br/>';
$temp .= '<b>E-mail | </b>' . $item->email . '<br />';
$temp .= '<br/>';
if ($item->tel > "")
{
$temp .= '<b>Phone | </b>'. $item->tel .''. $item->tele . '<br />';
$temp .= '<br/>';
}
if ($item->cell > "")
{
$temp .= '<b>Mobile phone | </b>'. $item->call .''. $item->cell . '<br />';
$temp .= '<br/>';
}
}
The other one returns a table and i use
$output = theme('table', array('header'=> $header, 'rows' => $rows, 'empty' => t("None")));
Now when I use
return $temp;
return $output;
It returns only one "output". If $temp if first it returns about teacher if $output is first then it renders a table without the teacher information.
This has nothing to do with Drupal, but is generic PHP. Return in PHP (and almost any language) means "return to the caller with this value". That means code after return is never ran.
return "foo";
print "I am never ran";
In your case, you want to glue the two strings together.
return $temp . $output;
The dot, concatenates two strings. and makes them one string.
you can return it as array.
$t_array['v1'] = $temp;
$t_array['v2'] = $output;
return $t_array;
I'm working on an online menu ordering system and I wanted to filter the data according to its category. I've tried to make it work with this code but it's only displaying one category.
**<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Scotch/Bourbon</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Brandy/Cognac</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Vodka/Gin/Tequila/Apertifs/Liqueur</a></li><br>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Beer/Softdrinks</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Cocktails</a></li>**
^ basically these are the categories and below is how display them.
**
<?php
$category = $_GET['choice'];
$category = str_replace('%', ' ', $category);
$query = "SELECT * FROM product_drinks WHERE drinks_cat = '" . $category . "'";
$result = mysql_query($query);
$total_records = mysql_num_rows($result); // the number of records in your result set
$num_cols = 2; // the number of columns
$num_rows = ceil($total_records / $num_cols); // the number of rows
$num = 0; // don't change this value, this is the first number of each record inside a record set
echo "<table style= 'cellpadding:8 width:100'>\n";
// next the loop for the table rows
for ($rows = 0; $rows < $num_rows; $rows++) {
echo "<tr bgcolor='black'>\n";
// this is the loop for the table columns
for ($cols = 0; $cols < $num_cols; $cols++) {
if ($num < $total_records) { // show records if available (reduce by one because the first record is no. "0" (zero)
// first create variables with the values of the current record
$title = mysql_result($result, $num, "drinks_name");
$clean_name = str_replace('_', ' ', $title);
$price = mysql_result($result, $num, "drinks_shot");
$price2 = mysql_result($result, $num, "drinks_bottle");
$category = mysql_result($result, $num, "drinks_cat");
$description = mysql_result($result, $num, "drinks_image");
$title = str_replace(' ', '%', $title);
echo "<td class='label'><a class='fancybox fancybox.ajax' href='food.php?drink=" . $title . "'>
<img src='" . mysql_result($result, $num, 'drinks_image') . "' class='masterTooltip' title= '" . $category . "'</a><br>";
echo "<td style='width:50%' class='desc'><b>" . $clean_name . "</b><br> Shot:<font style='color:#0072bc'> Php " . $price . "</font><br> Bottle: <font style='color:#724c0e'>Php " . $price2 . "</font></td>\n";
} else { // show an empty cell
echo "<td> </td>\n";
}
$num++; // raise the number by one for the next record
}
echo "</tr>\n"; // there are no more cols in this row, close the table row tag
}
echo "</table>\n"; // end of the region = closing tag for the table element
?>
**
I wish I could get over this wall. Please help~
First things first.
<?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?>
In the first chunk of code, you are using the same variable for all the links.
Are you passing different values for $category here. I believe you are not! and hence all the links are pointing to the same url.
You should use urldecode instead of str_replace('%', ' ', $category). (http://in2.php.net/urldecode)
Please indent your code so that it can be read and understood easily :)
The foreach construct below works just fine if the items returned are more than one. However, if there is only one item displayed the separator | is still being retained.
What's wrong with my code below?
<?php
foreach ($array->items as $item) {
$len = count($item);
if ($i < $len) {
print '' . $item->title . '' . ' | ';
}
else {
print '' . $item->title . '';
}
$i++;
}
?>
$echos=array();
foreach ($array->items as $item) {
$echos[]= '' . $item->title . '';
}
print implode(' | ', $echos);
for ($k = 0; $k < $count; $k++) {
$master[$k] = $namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k];
}
I'd like to declare a new array and set values from other arrays already declared. I thought I could just loop through the keys and set the values but this doesn't work for me.
Full code below. I'm parsing yellow pages search results and trying to output search results into a csv file. In the code below I removed the loop and only added a few values to the array to make sure my bug wasn't something else.
<?php
// include required functions
include('simple_html_dom.php');
$url = "http://www.yellowpages.com/" . $_POST['city'] . '-' . $_POST['state'] . '-' . $_POST['postalcode'] . '/' . $_POST['category'] . '?g=' . $_POST['city'] . '%2C+' . $_POST['state'] . '+' . $_POST['postalcode'] . '&q=' . $_POST['category'];
// get DOM from URL
$html = file_get_html($url);
// find all business name
foreach($html->find('h3.business-name') as $name)
//echo $name->innertext . '<br />';
$namearray[] = $name->innertext;
// find all business street address
foreach($html->find('span.street-address') as $street)
//echo $street->innertext . '<br />';
$streetarray[] = $street->innertext;
// find all business city
foreach($html->find('span.locality') as $locality)
//echo $locality->innertext . '<br />';
$localityarray[] = $locality->innertext;
// find all business state
foreach($html->find('span.region') as $region)
//echo $region->innertext . '<br />';
$regionarray[] = $region->innertext;
// find all business postal code
foreach($html->find('span.postal-code') as $postalcode)
//echo $postalcode->innertext . '<br />';
$postalcodearray[] = $postalcode->innertext;
// find all business phone
foreach($html->find('span.business-phone') as $phone)
//echo $phone->innertext . '<br />';
$phonearray[] = $phone->innertext;
?>
<p>Search results for: <?php echo $_POST['category'] . ' ' . $_POST['city'] . ' ' . $_POST['state'] . ' ' . $_POST['postalcode']; ?></p>
<?php
// Output results
$count = count($namearray);
for ($i = 0; $i < $count; $i++) {
echo $namearray[$i] . '<br />';
echo $streetarray[$i] . '<br />';
echo $localityarray[$i] . ',' . $regionarray[$i] . ' ' . $postalcodearray[$i] . '<br />';
echo $phonearray[$i] . '<br />' . '<br />';
}
$list = array (
array($namearray[0], $streetarray[0], $localityarray[0], $regionarray[0], $postalcodearray[0], $phonearray[0]),
array($namearray[1], $streetarray[1], $localityarray[1], $regionarray[1], $postalcodearray[1], $phonearray[1]),
array($namearray[2], $streetarray[2], $localityarray[2], $regionarray[2], $postalcodearray[2], $phonearray[2]),
array($namearray[3], $streetarray[3], $localityarray[3], $regionarray[3], $postalcodearray[3], $phonearray[3])
);
$fp = fopen('hrpsearch.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
Try:
$master = array();
for ($k = 0; $k < $count; $k++) {
$master[$k] = array
( $namearray[$k]
, $streetarray[$k]
, $localityarray[$k]
, $regionarray[$k]
, $postalcodearray[$k]
, $phonearray[$k]
);
}
This will create a new two-dimensional array for you with associated keys for every child array.
Try
for($k = 0; $k < $count; $k++) {
$master[$k] = array(
$namearray[$k],
$streetarray[$k],
$localityarray[$k],
$regionarray[$k],
$postalcodearray[$k],
$phonearray[$k]
);
}
Maybe do you just want to achieve this?
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
I would suggest using instead:
$master[$k]['name'] = $namearray[$k];
$master[$k]['street'] = $streetarray[$k];
...
The retrieval of the data will be more readable.
I think #DaveRandom's answer is what (I imply) you are looking for.
Since a PHP array can be of any type (scalar, array, object, etc.), you need to tell it you are assigning an array with the construct array().
The end result would be:
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
Try this
for ($k = 0; $k < $count; $k++) {
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
}
or is better to create associative array
for ($k = 0; $k < $count; $k++) {
$master[$k] = array('name'=>$namearray[$k],
'street'=>$streetarray[$k],
'city'=>$localityarray[$k],
'region'=>$regionarray[$k],
'postalCode'=>$postalcodearray[$k],
'phone'=>$phonearray[$k]);
}
You also need to check if your array elements are not empty or just put # befor array element like 'name'=>#$namearray[$k]. It will remove any warning if element doesn't exist.
I've got a rather complicated set of loops that pulls data out of mysql and compares it to values in an array and increments a counter. When I echo a flag when the counter is incremented, I get a bijilion flags (there're like 2600 records returned from the mysql query). But each time it prints, the counters are always 1 and when I print the counter's value at the end, it shows up as zero. It seems like something is re-setting the counter…
code
# ARRAY
$demographics=array(
"region"=>array(
"Northeast"=>array('total'=>0,'consented'=>0,'completed'=>0),
//more...
"West"=>array('total'=>0,'consented'=>0,'completed'=>0)
),"societal envirn"=>array(
"Urban"=>array('total'=>0,'consented'=>0,'completed'=>0)
),"age"=>array(
'18-19'=>array('total'=>0,'consented'=>0,'completed'=>0),
'20-24'=>array('total'=>0,'consented'=>0,'completed'=>0),
//more...
'55-59'=>array('total'=>0,'consented'=>0,'completed'=>0)
),
//more...
);
# LOOPS
while ($dbrecord = mysql_fetch_assoc($surveydata)) {
foreach ( $dbrecord as $dbfield=>$dbcellval ) {
foreach ( $demographics as $demographic=>$options ) {
foreach ( $options as $option=>&$counter ) {
if($demographic==="age"){
list($min,$max) = explode('-', $option);
if ($dbcellval >= $min && $dbcellval <= $max){
$counter['total']++;
echo '$' . $option . "['total'] = " . $counter['total'] . "<br />";
if ($dbrecord['consent']==="1"){
$counter['consented']++;
echo '$' . $option . "['consented'] = " . $counter['consented'] . "<br />";
if ($dbrecord['completion status']==="complete") {
$counter['completed']++;
echo '$' . $option . "['completed'] = " . $counter['completed'] . "<br />";
break 3;
} // if
} // if
break 2;
}
} // if age
else if ($option===$dbcellval){
$counter['total']++;
echo '$' . $option . "['total'] = " . $counter['total'] . "<br />";
if ($dbrecord['consent']==="1"){
$counter['consented']++;
echo '$' . $option . "['consented'] = " . $counter['consented'] . "<br />";
if ($dbrecord['completion status']==="complete") {
$counter['completed']++;
echo '$' . $option . "['completed'] = " . $counter['completed'] . "<br />";
break 3;
} // if
} // if
break 2;
} // else if $option==$dbcellval
} // foreach $options
} // foreach $demographics
} // foreach $dbrecord
} // while
sample output
$40-44['total'] = 1
$White['total'] = 1
$35-39['total'] = 1
$Northeast['total'] = 1 // the 'total' counter is 1
$Northeast['consented'] = 1
$Northeast['completed'] = 1
$South['total'] = 1
$Northeast['total'] = 1 // notice the 'total' counter is 1 again :(
$Northeast['consented'] = 1
$Northeast['completed'] = 1
You're defining counter from a foreach instruction, as $value in foreach($foo as $key=>$value), when using the foreach you only have a local copy of $counter.
You need to use either foreach($foo as $key=>&$value) or to refer to the full array path of your counter from $demographics.
You need to reference your array at each level, otherwise you are working on a copy of the data:
foreach ( $dbrecord as $dbfield=>$dbcellval ) {
foreach ( $demographics as $demographic => &$options ) {
foreach ( $options as $option => &$counter ) {
if($demographic==="age"){
list($min,$max) = explode('-', $option);
if ($dbcellval >= $min && $dbcellval <= $max){
$counter['total']++;
What if you simply stick with the $demographics variable.
i.e.
...
foreach ( $options as $option ) {
...
$demographics[$option]['total']++;
...