Last iteration of PHP foreach loop code change - php

I have a block of code thats working perfectly to pull data about different office locations.
What I would like to do is be able to make the last iteration of this loop change the div class to something else so I can apply a different set of css styles.
$fields = get_group('Offices');
foreach($fields as $field){
echo'<div class="oloc">';
if($locationVar==NULL || $locationVar!=$field['office-location'][1]) {
echo '<a name="' . strtolower(str_replace(' ', '-', $field['office-location'][1])) . '"></a><h3>' . $field['office-location'][1] . '</h3>';
$locationVar = $field['office-location'][1];
} else {
echo "<br />";
}
if($field['office-gm'][1]){
echo '<div class="gm"><img src="http://maps.googleapis.com/maps/api/staticmap?center=' . $field['office-gm'][1] . '&zoom=9&size=250x250&markers=color:blue|label:A|' . $field['office-gm'][1] . '&sensor=false"></div>';
}
if($field['office-name'][1]){
echo '<strong>' . $field['office-name'][1] . '</strong><br /><br />';
}
if($field['office-phone'][1]){
echo 'Phone: ' . $field['office-phone'][1] . '<br />';
}
if($field['office-fax'][1]){
echo 'Fax: ' . $field['office-fax'][1] . '<br />';
}
if($field['office-address'][1]){
echo '<br />Address:<br />' . strip_tags($field['office-address'][1], '<br><br />') . '<br />';
}
if($field['office-webpage'][1]){
echo 'Web: ' . 'Office Webpage<br />';
}
if($field['office-email'][1]){
echo 'Email: ' . 'Office Email<br />';
}
if($field['office-emp'][1]){
echo 'Jobs: ' . 'Employment Application<br />';
}
if($field['office-fb'][1]){
echo 'Facebook: ' . 'Facebook<br />';
}
if($field['office_office_twitter'][1]){
echo 'Twitter: ' . 'Twitter<br />';
}
echo '</div>';
}

For cases like these you can use a CachingIterator and the hasNext() method:
$fields = get_group('Offices');
$it = new CachingIterator(new ArrayIterator($fields));
foreach($it as $field)
{
...
if (!$it->hasNext()) echo 'Last:';
...
}

Put every echo in a var, this class definition in a other var. Then at the end of your foreach you check like so:
$i = 0;
foreach(...
if( $i == count($fields) ) { // change class }

Try this
$i = 0;
$total = count($fields);
$final = false;
foreach($fields as $field){
$i++;
$final = ($i + 1 == $total)? true : false;
if($final)
echo'<div class="NEW_CLASS">';
else
echo'<div class="oloc">';
....
}

First you should get the total count of the offices so that when you are on the last iteration, you can do something about it.
$fields = get_group('Offices');
$fields_count = count($fields);
$i = 0;
foreach ($fields as $field) {
$is_final = ++$i == $fields_count;
echo '<div class="oloc' . ($is_final ? ' oloc-final' : '') . '">';
[...]
}

Related

How to get array from API

I want to get the episode number and Released from
http://www.omdbapi.com/?t=the+walking+dead&season=6&r=json
but I don't know how to extract arrays from the api.
Can someone help me?
My code is:
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json=file_get_contents("http://www.omdbapi.com/?t=$title2&season=6&r=json");
$details=json_decode($json);
if($details->Response=='True')
{
$episodios=$details->Episodes;
}
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json = file_get_contents("http://www.omdbapi.com/?t=$title2&season=6&r=json");
$details = json_decode($json);
if ($details->Response == 'True') {
echo 'There are ' . count($details->Episodes) . ' episodes<br />';
foreach ($details->Episodes as $key => $episode) {
echo 'Episode criteria number is ' . ($key + 1) . '<br />';
echo 'Episode Number: ' . $episode->Episode . '<br />';
echo 'Released: ' . $episode->Released . '<br />';
}
}
<?php
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json=file_get_contents("http://www.omdbapi.com/t=$title2&season=6&r=json");
$details=json_decode($json);
if($details->Response=='True')
{
$episodios=$details->Episodes;
foreach ($episodios as $episode) {
echo 'Episode Number: ' . $episode->Episode . '<br />';
echo 'Released Date: ' . $episode->Released . '<br />';
}
}
?>

how can i make a span element in this line of php

I what to put a span element for $term['nodes']
I have tried to put after bracket and between but nothing works for me
if (isset($term['nodes'])) {
$term['name'] = $term['name'] . ' (' . $term['nodes'] . ')';
}
here is the all functin
function bootstrap_taxonomy_menu_block($variables) {
$tree = $variables['items'];
$config = $variables['config'];
$num_items = count($tree);
$i = 0;
$output = '<ul class="nav nav-pills nav-stacked">';
foreach ($tree as $tid => $term) {
$i++;
// Add classes.
$attributes = array();
if ($i == 1) {
$attributes['class'][] = '';
}
if ($i == $num_items) {
$attributes['class'][] = '';
}
if ($term['active_trail'] == '1') {
$attributes['class'][] = 'active-trail';
}
if ($term['active_trail'] == '2') {
$attributes['class'][] = 'active';
}
// Alter link text if we have to display the nodes attached.
if (isset($term['nodes']))
{
$term['name'] = $term['name'] . ' (<span>' . $term['nodes'] . '</span>)';
}
// Set alias option to true so we don't have to query for the alias every
// time, as this is cached anyway.
$output .= '<li' . drupal_attributes($attributes) . '>' . l($term['name'], $term['path'], $options = array('alias' => TRUE));
if (!empty($term['children'])) {
$output .= theme('taxonomy_menu_block__' . $config['delta'], (array('items' => $term['children'], 'config' => $config)));
}
$output .= '</li>';
}
$output .= '</ul>';
return $output;
}
i what this for the bootstrap cdn class , i have move the function on template.php , of drupal theme , but the span element is in plain text in browser
Try this:
if (isset($term['nodes']))
{
$term['name'] = $term['name'] . ' (<span>' . $term['nodes'] . '</span>)';
echo $term['name']; // To see the output
}

PHP Array Declaration

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.

Web service Array problem

I have this web service http://onleague.stormrise.pt:8031/OnLeagueRest/resources/onleague/Social/Login?Token=210029242357724|fd4eef8a839f24db2a9fedcd.1-100001001235070|Nro7dAY411DJRn7E8zB6MOXHjq8
And I'm having problems catching some values like:
clubId, clubName, clubLogo, relationType, and dateAdded.
I just don't know how to handle the array.
My code:
<?php
function getUserInfo() {
$json = file_get_contents('http://onleague.stormrise.pt:8031/OnLeagueRest/resources/onleague/Social/Login?Token=210029242357724|fd4eef8a839f24db2a9fedcd.1-100001001235070|Nro7dAY411DJRn7E8zB6MOXHjq8');
$data = json_decode($json, TRUE);
$v= $data['data'];
$_SESSION['userinfid'][] = $v['id'];
$_SESSION['userinfnickname'][] = $v['nickname'];
$_SESSION['userinfvisibility'][] = $v['visibility'];
$_SESSION['userinffirstname'][] = $v['first_name'];
$_SESSION['userinflastname'][] = $v['last_name'];
$_SESSION['userinfgender'][] = $v['gender'];
$_SESSION['userinfdialect'][] = $v['dialect'];
$_SESSION['userinfstatus'][] = $v['status'];
$_SESSION['userinfadmissiondate'][] = $v['admission_date'];
$_SESSION['userinflastaccess'][] = $v['last_access'];
$_SESSION['userinfusername'][] = $v['username'];
$_SESSION['userinfpoints'][] = $v['points'];
$_SESSION['userinfranking'][] = $v['ranking'];
$_SESSION['userinfsessionID'][] = $v['sessionID'];
$_SESSION['userinfpublicProfile'][] = $v['publicProfile'];
$_SESSION['userinfemail'][] = $v['email'];
$_SESSION['userinfmobile'][] = $v['mobile'];
$_SESSION['userinfimageURL'][] = $v['imageURL'];
$_SESSION['userinfclubURL'][] = $v['clubURL'];
$_SESSION['userinfcontact'][] = $v['contacts']['contact'];
$_SESSION['userinfcontactType'][] = $v['contacts']['contactType'];
$_SESSION['userinfisdefault'][] = $v['contacts']['is_default'];
$_SESSION['userinfclubId'][] = $v['clubs']['clubId'];
$_SESSION['userinfclubName'][] = $v['clubs']['clubName'];
$_SESSION['userinfclubLogo'][] = $v['clubs']['clubLogo'];
$_SESSION['userinfrelationType'][] = $v['clubs']['relationType'];
$_SESSION['userinfdateAdded'][] = $v['clubs']['dateAdded'];
}
getUserInfo();
echo 'IDClube: ' . $_SESSION['userinfclubId'][0] . '<br />';
echo 'NomeClube: ' . $_SESSION['userinfclubName'][0] . '<br />';
echo 'LogoClube: ' . $_SESSION['userinfclubLogo'][0] . '<br />';
echo 'RelationType: ' . $_SESSION['userinfrelationType'][0] . '<br />';
echo 'DataAdicionado: ' . $_SESSION['userinfdateAdded'][0] . '<br />';
?>
And if there is only one value for each key of session then
<?php
function getUserInfo() {
$json = file_get_contents('http://onleague.stormrise.pt:8031/OnLeagueRest/resources/onleague/Social/Login?Token=210029242357724|fd4eef8a839f24db2a9fedcd.1-100001001235070|Nro7dAY411DJRn7E8zB6MOXHjq8');
$data = json_decode($json, TRUE);
$v= $data['data'];
foreach($v as $key => $value)
{
$_SESSION['userinf'.$key] = $value;
}
}
getUserInfo();
echo 'IDClube: ' . $_SESSION['userinfclubs']['clubId'] . '<br />';
echo 'NomeClube: ' . $_SESSION['userinfclubs']['clubName'] . '<br />';
echo 'LogoClube: ' . $_SESSION['userinfclubs']['clubLogo'] . '<br />';
echo 'RelationType: ' . $_SESSION['userinfclubs']['relationType'] . '<br />';
echo 'DataAdicionado: ' . $_SESSION['userinfclubs']['dateAdded'] . '<br />';
Be careful,there's more than one club in clubs, so you'll need to do something like this :
foreach ($v['clubs'] as $value) {
$_SESSION['userinfclubId'][] = $value['clubId'];
$_SESSION['userinfclubName'][] = $value['clubName'];
$_SESSION['userinfclubLogo'][] = $value['clubLogo'];
$_SESSION['userinfrelationType'][] = $value['relationType'];
$_SESSION['userinfdateAdded'][] = $value['dateAdded'];
}

I have var_dump a variable and it is empty

I want to know the reasons why this variable is passing empty.
<form action="cart.php" method="POST">
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="' . $variety['price'].'_'. $variety['variety']. '_'. $product['name'] . ' " /></form>
Can you see $product['name'] how can I print the it's value after extracting it's values in cart.php as
extracts values
list($aDoor, $variety,$productname) = split('_', $_POST['price']);
$aDoor = array();
$variety = array();
$productname= array();
foreach ($_POST['price'] as $p)
{
list($a, $b,$c) = explode('_', $p);
$aDoor[] = $a;
$variety[] = $b;
$productname[] = $c;
}
Now below the foreach loop how can I echo the print of productname once..?
foreach($productname as $name) {
echo $name . '<br />';
}
or if you want to associate the product names with their other values in $aDoor and $variety you could do:
foreach($productname as $index => $name) {
echo 'Name: ' . $name . '<br />';
echo 'Variety: ' . $variety[$index] . '<br />';
echo 'Price: ' . $aDoor[$index] . '<br />';
}
EDIT:
If I can take your comment to mean that all of the names are the same in the $productname array then you can do this instead:
if(count($productname) > 0) {
echo 'Product Name: ' . $productname[0] . '<br />';
foreach($variety as $index => $name) {
echo $name . ': $' . $aDoor[$index] . '<br />';
}
}
Now below the foreach loop how can I
echo the print of productname once..?
print_r ($productname);
But if you want to see each value of product name inside the loop:
foreach ($_POST['price'] as $p)
{
list($a, $b,$c) = explode('_', $p);
$aDoor[] = $a;
$variety[] = $b;
$productname[] = $c;
echo $c . '<br />'; // show product name
}
Also, i don't see your echoing this line of code with php:
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="' . $variety['price'].'_'. $variety['variety']. '_'. $product['name'] . ' " /></form>
in which case this is not how to show value in above line:
value="' . $variety['price'].'_'. $variety['variety']. '_'. $product['name'] . ' "
instead you need to wrap it in php tags:
value="<?=$variety['price'].'_'. $variety['variety']. '_'. $product['name']?>"
As I stated in another of your questions, you cannot use split() on an array. You're forcing PHP to treat $_POST['price'] as an array by naming it "price[]" in your form. WHen you split on an array:
$arr = array('a', 'b', 'c');
list($a, $b, $c) = split($arr);
you end up with the following:
$a = 'Array';
$b = NULL;
$c = NULL;
You will have to do the following:
list($aDoor, $variety,$productname) = explode('_', $_POST['price'][0]);
^^^ (note the array notation)
You're also not creating a $product variable in your extractions cript. You are creating a $productname array, but $productname is not the same as $product['name']

Categories