I'm trying to create a dynamic navigation menu.
All allowed possibilities are defined in an array.
I'm trying to count the array, split it in half and print each half of the array into seperate div's. One on the left side of the screen and the other on the right side.
this is what i've got:
function menu_main() {
$count = count($GLOBALS['menu']);
$count = round($count / 2);
$menu_1 = array_slice($GLOBALS['menu'], 0, $count);
$menu_2 = array_slice($GLOBALS['menu'], $count++);
echo ' <div id="menu_1">' . "\n";
foreach($menu_1 as $page) {
echo ' <div class="menu_items">' . "\n";
echo ' <a class="menu" href="index.php?page=' . $page . '">' . $page . '</a> .' . "\n"; //Create menu left
echo ' </div>'. "\n";
}
echo ' </div>'. "\n";
echo ' <div id="menu_2">' . "\n";
foreach($menu_2 as $page) {
echo ' <div class="menu_items">' . "\n";
echo ' <a class="menu" href="index.php?page=' . $page . '">' . $page . '</a> .' . "\n"; //Create menu right
echo ' </div>'. "\n";
}
echo ' </div>'. "\n";
}
Is there a way to do this with itteration?
This works but it looks way to messy.
Ok, a couple of things:
$GLOBALS['menu'];
Why use $GLOBALS, or global $menu, for that matter? Why not pass what you need to the function?
function menuMain(array $menu)
{
$count = floor(count($menu)/2);
Would make a lot more sense. Also:
$menu_1 = array_slice($GLOBALS['menu'], 0, $count);
$menu_2 = array_slice($GLOBALS['menu'], $count++);//<== why the increment?
Why are you incrementing $count, only to then not use it anymore? You're post-incrementing the value, which means that if $count is 10, then the code above is evaluated to:
$menu_1 = array_slice($GLOBALS['menu'], 0, 10);
$menu_2 = array_slice($GLOBALS['menu'], 10);//10+1 happens AFTER the array_slice call is made
Also don't use "\n", because line-feeds are system dependent, PHP has a predefine constant for this reason: PHP_EOL. Use it (that's an order).
And don't concatenate what you echo, just comma-separate it:
echo 'foo', 'bar', PHP_EOL;
echo 'foo'.'bar'.PHP_EOL;
both may produce the same time, but the first version is faster, because the strings are pushed to the output, without first concatenating them into a new string.
Not that it matters here, because functions should return something, not echo it.
Anyway, your question: is there a way to do this with iteration? Yes, and you're already iterating (foreach iterates an array/object).
An alternative approach would be:
function mainMenu (array $menu)
{
$return =' <div id="menu_1">' . PHP_EOL;//functions shouldn't echo
//start with div 1
for($i = 0, $j= count($menu), $count = floor($j/2); $i<$j;++$i)
{
if ($i == $count)
{//reached half-way marker, close div 1, open div 2
$return .= '</div>'.PHP_EOL.'<div id="menu_2">'.PHP_EOL;
}
$return .= ' <div class="menu_items">' . PHP_EOL
.' <a class="menu" href="index.php?page=' . $menu[$i] . '">' . $menu[$i]
. '</a> .' .PHP_EOL;
}
return $return.'</div>';//close div2 and return
}
That should give you the exact same output as before, only it only uses a single loop, doesn't rely on globals, and doesn't echo things, so you call it like this:
$menu = array('your', 'global', 'array');
echo mainMenu($menu);//pass the array, echo what it returns
My solution if it helps.
$menu = array ("link1","link2","link3","link4","link5");
function menu_main()
{
global $menu;
$count = count($menu);
$menu_items = round($count / 2);
//initialize the divs for menus
$output_menu[0] = ' <div id="menu_1">' . "\n";
$output_menu[1] = ' <div id="menu_2">' . "\n";
$menu_count = 0;
foreach($menu as $link)
{
if ($menu_count < $menu_items)
{
//what enters in first menu
$output_menu[0] .= ' <div class="menu_items">' . "\n";
$output_menu[0] .= ' <a class="menu" href="index.php?page=' . $link . '">' . ucfirst($link) . '</a> .' . "\n"; //Create menu left
$output_menu[0] .= ' </div>'. "\n";
}
else
{
//what enters in second menu
$output_menu[1] .= ' <div class="menu_items">' . "\n";
$output_menu[1] .= ' <a class="menu" href="index.php?page=' . $link . '">' . ucfirst($link) . '</a> .' . "\n"; //Create menu left
$output_menu[1] .= ' </div>'. "\n";
}
$menu_count++;
}
//close the divs for menus
$output_menu[0] .= ' </div>'. "\n";
$output_menu[1] .= ' </div>'. "\n";
//return array with content for menus
return $output_menu;
}
$menu_main = menu_main(); // get content in variable
print_r($menu_main[0]); //print 1st menu
print_r($menu_main[1]); //print 2nd menu
Related
I'm trying to re-write this code so that it goes with the columns that are going to be user-defined. With this, my challenge consists of
a) Needs to select random starting item from array
b) Select the next random color from the original array that is not equivalent to the most recent items selected based the number: $intNotesColumn + 1
I was thinking a do-while statement nested inside another was appropriate for this but am unsure how to go about this. Here is my code so far:
$metroUIcolors = array( "#A30061", "#8200CC", "008987", "#A05000", "#B85A93", "#C07807", "#E51400", "#297A29" );
$metroUIcolorsLength = count($metroUIcolors);
$intNotesColumn = 3; // This will be user-defined later
// Now I query the SQL database to get my base-code
if ($result->num_rows > 0) {
// output data of each row
echo '<table border=0 valign=top>'
. '<tr>'
. '<td colspan=' . $intNotesColumn . '>' . '<h1>header</h1>' . '</td>'
. '</tr>'
. '<tr>';
$counterRank = 1;
while($row = $result->fetch_assoc()) {
echo "<td bgcolor=" . $metroUIcolors[rand(0, $metroUIcolorsLength - 1)]. ">"
. "<h2>" . $row["username"] . '</h2><br />'
. "<p class='notes'>" . $row["notes"] . "</p>"
. "<p class='footnotes'>"
. "<br />Last Reset: " . $row["lastReset"]
. '<br />Last Update: ' . $row['lastUpdate']
. '<br />SessionID: ' . $row["sessionID"]
. "<br />Counter = " . $counterRank . "</td>". '</p>';
if ($counterRank % $intNotesColumn == 0)
{
echo '</tr><tr>';
}
$counterRank++;
}
echo '</tr></table>';
} else{
echo "No Notes Found in databases";
}
Then, why don't you do it order picking one color at a time. You could use shuffle() so that there will be a different starting color everytime.
<?php
$counterRank = 1;
// shuffle the array
shuffle($metroUIcolors);
while($row = $result->fetch_assoc()) {
$rand_color = $counterRank % $metroUIcolorsLength;
echo "<td bgcolor=" . $metroUIcolors[$rand_color]. ">";
// everything else
$counterRank++;
}
?>
If you insist on doing the way you said, you may create an array $colorCount which has color codes as keys and count as values.
<?php
$counterRank = 1;
$colorCount = array_fill_keys($metroUIcolors, 0);
while($row = $result->fetch_assoc()) {
do {
$rand_color = $metroUIcolors[rand(0, $metroUIcolorsLength - 1)];
} while ($colorCount[$rand_color] > 5);
echo "<td bgcolor=" . $rand_color. ">";
// everything else
$counterRank++;
$colorCount[$rand_color] += 1;
}
?>
I have the below code:
function cat_fields($fields)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$fields['cat_flink'] = '<a id="a' . count($fields) . '" href="' . $fields['cat_furl'] . '" title="' . $fields['cat_title'] . '">' . $fields['cat_name'] . '</a>';
return $fields;
}
And i am trying to count each field of $fields['cat_flink'] = '<a id="a' . count($fields) . '" I tried with id="a' . count($fields) . '" but it's returning the total number of field instead of counting them. How can i count them EACH.
Should be
<a id="a1"....>
<a id="a2"....>
Instead it's echoing me
<a id="15"....>
<a id="15"....>
..... and so on
Please help me on this matter.
You're trying to count all the fields in your array; Quoted from the PHP Manual:
Counts all elements in an array, or something in an object.
To get indices (i.e. the numbers you're looking for), you will have to set a starting number and loop over all your fields until you've got them all, and increment that number everytime your walk through the loop.
Your method however, seems to be for only one iteration, which means you would have to store your number elsewhere. A good way to do this would be adding the number as a parameter to your function:
function cat_fields($fields, $number)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$fields['cat_flink'] = '<a id="a' . $number . '" href="' . $fields['cat_furl'] . '" title="' . $fields['cat_title'] . '">' . $fields['cat_name'] . '</a>';
return $fields;
}
Having done that you should edit the loop (I presume) you're using to call the function multiple times:
for ($i = 1; $i < count($yourArray); $i++) {
// code
$foo = cat_fields($yourArray, $i);
// more code
}
Hope that helps.
EDIT:
I've edited the pastebin from lines 131-141:
if(($rs = $db->execute($sql)) && (!$rs->EOF))
{
$i = 1;
while(!$rs->EOF)
{
$rs->fields = seoscripts_prepare_cat_fields($rs->fields, $i);
$tpl->assign_array_d('tool_category_row', $rs->fields);
$tpl->parse_d('tool_category_row');
$rs->MoveNext();
$i += 1;
}
}
Counting like thatcount($fields) returns the numbers of fields you have you need to add a integer like i=0;
and increase it i++;
Try this
function cat_fields($fields)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$i=0;
foreach($fields as $field)
{
$fields['cat_flink'] = '<a id="a'.$i.'" href="' . $field['cat_furl'] . '" title="' . $field['cat_title'] . '">' . $field['cat_name'] . '</a>';
i++;
}
return $fields;
}
Try this
function cat_fields($fields)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$str = '';
$i = 0;
foreach($fields as $field)
{
$str . = '<a id="a' . $i . '" href="' . $fields['cat_furl'] . '" title="' . $fields['cat_title'] . '">' . $fields['cat_name'] . '</a>';
$i++;
}
$fields['cat_flink'] = $str;
return $fields;
}
if you are counting an array then
echo count($array);
will give the count of every element in the array.
I'm working on the php code of someone else and have a problem with the user/menu language. This is the code of the page with the dynamic price list for banner ads on this website. Depending on the selected menu language, the user can see the price of the banner ads which are for each menu language different.
Whenever the user is coming to this page the active banner ads price should be for the users menu language. Right now it's fixed on russian language and I don't know how to make it dynamicly or at least change/fix it to english.
Please have a look and let me konw if you might see a solution. Thanks!
<?php
class reklama_content
{
private $db;
private $cms;
private $valid;
private $data;
private $tools;
public function __construct()
{
$reg = Registry::getInstance();
$this->db = $reg->get('db');
$this->cms = $reg->get('cms');
$this->valid = $reg->get('Validate');
$this->data = $reg->get('methodData');
$this->tools = $reg->get('tools');
}
public function get_reklama_content()
{
$lang = language::getLang();
if ($_GET['ryb'])
$ryb = $_GET['ryb'];
else
$ryb = 'banners';
if ($ryb == 'banners')
$ret = $this->getBanner($lang);
elseif ($ryb == 'classifieds')
$ret = $this->getClassifieds($lang);
return $ret;
}
public function getClassifieds($lang)
{
$contetn = $this->db->selectArray($this->db->Select('*', 'block', "`name` = 'classifieds_content'"));
$ret = $contetn['content_' . $lang];
return $ret;
}
public function getBanner($lang)
{
$header = array();
$top = array();
$center = array();
$bottom = array();
$banners = $this->db->selectAssoc($this->db->Select('*', 'banners', false, 'page_id', false, true));
$contetn_top = $this->db->selectArray($this->db->Select('*', 'block', "`name` = 'reklams_baner_top'"));
$contetn_bottom = $this->db->selectArray($this->db->Select('*', 'block', "`name` = 'reklams_baner_bottom'"));
foreach ($banners as $x => $y) {
if ($y['position'] == 'header')
$header[$x] = $y;
elseif ($y['position'] == 'top')
$top[$x] = $y; elseif ($y['position'] == 'center')
$center[$x] = $y; elseif ($y['position'] == 'bottom')
$bottom[$x] = $y;
}
$ret = $contetn_top['content_' . $lang];
$langs = ($this->tools->getAllLang(true));
$ret .= '
<hr style="width: 100%; margin: 40px 0;" />
<div class="rek_banner_conteiner header_conteiner">
<span class="ban_title">' . l::top_banner1() . '</span>
<img src="styles/them_01/img/banner_468x60.jpg" class="header_example" />
<div class="lang_menu">' . l::menu_language1() . '<br />';
$ret .= '<span id="eng_header" >' . l::english() . '</span>';
$ret .= '<span id="de_header" >' . l::german() . '</span>';
$ret .= '<span id="rus_header" >' . l::russian() . '</span>';
$ret .= '<span id="tr_header" >' . l::turkish() . '</span>';
$ret .= '</div>';
foreach ($langs as $z => $g) {
$ret .= '
<div id="' . $g['name'] . '_header_box" class="hide">
<table>
<tr class="order_table_title">
<td class="order_table_position">' . l::location() . '</td>
<td class="order_table_size">' . l::size1() . '</td>
<td class="order_table_date">' . l::fee_per_month() . '</td>
</tr>
';
foreach ($header as $z => $f) {
$page = $this->db->selectArray($this->db->Select('title_' . $lang, 'pages', "`id` = '" . $f['page_id'] . "'"));
$ret .= '<tr>
<td>' . $page['title_' . $lang] . '</td>
<td>' . $f['size'] . '</td>
';
if ($f['price' . '_header_' . $g['name']])
$ret .= '<td>$ ' . $f['price' . '_header_' . $g['name']] . '</td>';
else
$ret .= '<td></td>';
$ret .= '
</tr>';
}
$ret .= '
</table>
</div>
';
}
$ret .= '</div>';
$ret .= $contetn_bottom['content_' . $lang];
return $ret;
}
}
?>
I have code in an answer about language detection here. It contains a cool little easily modifiable snippet I use to check who's coming from where based on their browser preferences for language. In short, you'll need to either detect the language from $_SERVER['HTTP_ACCEPT_LANGUAGE'] or detect a user preference (eg. ?lang=de ) to override their default language preference in their browser. That's if you're not using a custom URL like tr.example.com. Then you can do a switch(). Right now it looks like you're concatenating all of the language <span> tags together.
switch($lang){
case "ru":
//Russian
$ret .= '<span id="rus_header" >' . l::russian() . '</span>';
break;
case "de":
//German
$ret .= '<span id="de_header" >' . l::german() . '</span>';
break;
case "tr":
//Turkish
$ret .= '<span id="tr_header" >' . l::turkish() . '</span>';
break;
default:
//English
$ret .= '<span id="eng_header" >' . l::english() . '</span>';
}
As my other post says (there's a video from Google). Ideally it's best if you have the content all in one language on a specific URL for that language. Then all of this magical language translation stuff happens without the user having to make a selection or guess if they're clicking the correct link in a language they're not familiar with.
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' : '') . '">';
[...]
}
I'm trying to figure out someone else's code and have come across this piece of code:
$html = '<div class="event">' . "\n";
if (get ( 'Event_Image' ))
{
$html .= '<a href="' . get ( 'Event_Image' ) . '">'
. '<img src="' . pt () . '?src=' . get ( 'Event_Image' ) . '&w=100" alt="' . get_the_title () . '" />'
. '</a><br />' . "\n";
}
$html .= '<a href="' . get_permalink ( $eventId ) . '">' . // title="Permanent Link to ' . get_the_title_attribute() . '"
get_the_title () . '</a><br />' . "\n";
if (get ( 'Event_Time' ))
{
$html .= get ( 'Event_Time' ) . '<br />' . "\n";
}
if (get ( 'Store_Location' ))
{
$html .= get ( 'Store_Location' );
}
$html .= '</div><!-- event -->' . "\n";
$eventsArr [$dateArr] [$eventId] = $html;
}
My question: What does the .= mean? Does it add to the variable (in this case $html)?
Yes. See http://www.php.net/manual/en/language.operators.string.php.
It means concatenate/append the value on the right hand to the value stored in the variable:
$a = 'str';
$a .= 'ing';
echo $a; // string
Yes, you got it right, here is an example:
$str = 'Hello ';
$str .= 'World';
echo $str;
Result:
Hello World
It means concatinate equals. So
$var = 'foo';
$var .= 'bar';
echo $var;
// output is 'foobar'
It is concatenate, then assign.
Same as:
$html = $html . $someString;