Using Data attributes With Data from an array - php

I am using data-attributes in my portal page to describe favorite links. This is very easy to do it you are using a regular list ( because you can individually put the custom "data-special" in.
However when you have lots of links in an array and you are using foreach how do you pick out and apply a data-special to individual links within the array? ? the way I see it its either all or none within the foreach.
data-special is my own declaration. I apply a Unicode character through CSS to the links that are special.
Thank you for reading and your time.
$portal = array(
"Twitter" => "http://twitter.com",
//another 20 array elements
);
ksort($portal);
foreach ($portal as $key => $item):
echo("<li><a rel=\"external\" href=\"$item\">$key</a></li>");
?>
<?php endforeach; ?>
I need to add data-special to specific links but am unsure of how to pick them out as they are in an array
EDIT
This is what I am trying to achieve on perhaps 5 of some links in the array
<li data-special>Kular</li>

Without knowing any more, try something like this (filling in the blanks where required). I'm assuming you're using the UTF-8 content type
<?php foreach ($portal as $key => $item) :
$special = /* boolean statement; is $key or $item special */
? 'data-special="true"' : '';
?>
<li <?php echo $special ?>>
<a rel="external"
href="<?php echo htmlspecialchars($item, ENT_QUOTES, 'UTF-8') ?>">
<?php echo htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>
</a>
</li>
<?php endforeach ?>
A more concrete example might be if you wanted to set only the Twitter key to special..
$special = $key == 'Twitter'
? 'data-special="true"' : '';
Perhaps a better example might be...
// before the foreach loop
$specials = array('Twitter', 'Google', 'Facebook');
then, in your loop
$special = in_array($key, $specials)
? 'data-special="true"' : '';

Related

PHP foreach loop skip first 3 items

I have a list of 6 products that i want to split in 2 lists of 3 products next to each other. The list are made within a foreach loop, the first list stops after the count == 2, so 3 items wil be displayed. The second list should start with the fourth item. How can i achieve this?
This is wat makes the first list of 3 items:
<?php
$_categoryId = explode(' ', $category['id']);
$count = 0;
$_productCollection = Mage::getModel('catalog/category')->load($_categoryId)
->getProductCollection()
->addAttributeToSelect('*')
->setOrder('date_added', 'DESC');
?>
<?php foreach ($_productCollection as $_product): ?>
<li class="category-row-list-item">
<a class="product-name" href="<?php echo $_product->getProductUrl() ?>">
<?php echo $this->htmlEscape($_product->getName()) ?>
</a>
</li>
<?php
if($count == 2) break; // Stop after 3 items
$count++;
?>
<?php endforeach ?>
Best regards,
Robert
For simplicity you could repeat the foreach statement but doing the opposite and continue on the first three items.
<?php foreach ($_productCollection as $_product): ?>
<?php
$count++; // Note that first iteration is $count = 1 not 0 here.
if($count <= 3) continue; // Skip the iteration unless 4th or above.
?>
<li class="category-row-list-item">
<a class="product-name" href="<?php echo $_product->getProductUrl() ?>">
<?php echo $this->htmlEscape($_product->getName()) ?>
</a>
</li>
<?php endforeach ?>
The keyword continue is used in loops to skip the current iteration without exiting the loop, in this case it makes PHP go directly back to the first line of the foreach-statement, thus increasing counter to 4 (since 4th, 5th and 6th is what we're after) before passing the if statement.
Commentary on the approach
I kept it coherent with your existing solution but a more clean way in this case would probably be to use the built in Collection Pagination.
If you use ->setPageSize(3) you can simply iterate the collection to get the first three products and then use ->setCurPage(2) to get the second page of three items.
I'm linking this blog post on the topic here just to give you an example of how it's used but since I don't know your comfort level in working with collections I retain my first answer based on your existing code.
Something like that with modulo function for have new array each 3 items :
$count = 1;
$count_change = 1;
$key = 0;
$yourList = array(
"1",
"2",
"3",
"4",
"5",
"6",
);
foreach ($yourList as $item) {
if (!isset($$new_list)) {
$new_list = "list" . $count_change . "";
$$new_list = array();
}
if ($count % 3 == 0) {
$key = 0;
$count_change++;
$new_list = "list" . $count_change . "";
$$new_list = array();
}
$$new_list[$key] = $item;
$count++;
$key++;
}
Hope this helps.

Include single lines of php in ordered list

I am fairly new to php and not sure if it is possible to include php file content line by line.
Say I have an ordered list and a php file with three lines. I can include the whole content using
<?php include 'myfile.php' ?>
my question is, if it is possible to include single lines.
myfile.php
apples
bananas
oranges
index.php
<ol>
<li>???????</li>
<li>???????</li>
<li>???????</li>
</ol>
Thanks
There are more possibilities one of them is to put your content in a text file and load the content with file for example. Then you can iterate through every line with foreach.
The other way is to put your values in an array if your don't need it in a file.
$fruits = array(
'apples',
'bananas',
'oranges'
);
Then you can iterate with foreach over that array.
http://php.net/manual/en/language.types.array.php
Before you start you should read about that things and perhaps you start at the beginning of that documentation.
You can read in the file as an array:
$myFile = file('myfile.php', FILE_IGNORE_NEW_LINES); // FILE_IGNORE_NEW_LINES strips the new line characters from the array
now you can either print a single line:
echo $myFile[2]; // echo the third item
or output everything as a HTML list:
echo '<ol>';
foreach ($myFile as item) {
echo '<li>'. $item .'</li>';
}
echo '</ol>';
You can do in various ways:
declaring variables for each one:
myfile.php
<?php
$apples = "apples";
$bananas = "bananas";
$oranges = "oranges";
and print them in the list:
index.php
<ol>
<li><?php echo $apples; ?></li>
<li><?php echo $bananas; ?></li>
<li><?php echo $oranges; ?></li>
</ol>
OR declaring one array with all of them.
myfile.php
<?php
$fruits = array( 'apples', 'bananas', 'oranges' );
and print them in the list using a foreach:
index.php
<ol>
<?php
foreach ($fruits as $fruit){
echo '<li>'.$fruit.'</li>';
}
?>
</ol>
Good Luck!

Display meta description outside single post - WordPress

This is my first question here, hope to be useful in future to someone. We work on a WordPress site now, and try to display meta description content generated by All In One Seo plugin outside the loop. It's not a problem when it's on page/post. The code that works for single is
<?php $metadesc = get_post_meta($post->ID, '_aioseop_description', true);
if ($metadesc) {
echo $metadesc;
} else {
the_excerpt();
}
?>
Later on the other day I came with this solution
<?php $mykey_values = get_post_custom_values('_aioseop_description');
foreach ( $mykey_values as $key => $value ) {
echo "$value";
} ?>
I'm not sure if it's good to use this one, the problem I have now is that I want to display exact number of symbols, not all the content.
Well it was pretty lame question, but sometimes when you are stuck it's hard to see simple things. This is my final code which do the work for me:
<?php $mykey_values = get_post_custom_values('_aioseop_description');
foreach ( $mykey_values as $key => $value ) {
echo substr("$value",0 ,150); //This will display the first 150 symbols
} ?>

PHP Multidimensional Arrays

I'm trying to make a universal script that adds keywords to my individual pages (since header is in an include file) so I am getting the end of the url (multi.php) and retrieving the desc etc. from it's array. For some reason instead of returning keywords or descriptions it instead just returns "m" . . . it's kind of random and has me scratching my head. Here's what I got
<html>
<head>
<title>Multi-Demensional Array</title>
<?php
$path = pathinfo($_SERVER['PHP_SELF']);
$allyourbase = $path['basename'];
$pages = array
(
"multi.php" => array
(
"keywords" => "index, home, test, etc",
"desc" => "This is the INDEX page",
"style" => "index.css"
),
"header.php" => array
(
"keywords" => "showcase, movies, vidya, etc",
"desc" => "SHOWCASE page is where we view vidya.",
"style" => "showcase.css"
)
);
?>
</head>
<body>
<?php
foreach($pages as $key => $value)
{
if($key == $allyourbase)
{
echo $key['desc'];
}
}
?>
</body>
</html>
The reason why this is happening is because in PHP if I had the following code:
$hello = 'world';
and I attempted to do the following:
echo $hello[0];
PHP Would treat the string as an array and return me whatever is in position 0, which would result in w, when your using a foreach your asking PHP to set the key of the array to $key, and it's value to $value.
you then echo echo $key['desc'];, as the value is a string, php sees it as an integer based index, so it will ignore your call for desc and then return the first index, if you were to change echo $key['desc'] to echo $value['desc'] which is a hash based array it will return the desired results.
You should just be able to do this:
if(isset($pages[$allyourbase]))
{
echo $pages[$allyourbase]['desc'];
}
No need for the loop
try
echo $key['desc'];
replace with
echo $value['desc'];
Other people have provided some great solutions, but it's important that you understand exactly what is happening here, so you don't make the same mistake again. Pay careful attention to the comments, and you will be on your way to successful coding!
Here's what is happening:
foreach ($pages as $key => $value) {
if ($key == $allyourbase) {
// At this point: $key = 'multi.php'
// Also: $value = array( ... );
// Keep in mind: $key['desc'] = $key[0] = 'm';
// You are grabbing the first letter of the 'multi.php' string.
// When dealing with strings, PHP sees $key['desc'] as $key[0],
// which is another way to grab the very first character of 'multi.php'
echo $key['desc'];
// You really want $pages[$key]['desc'], but below
// is a better way to do it, without the overhead of
// the loop.
}
}
If you kept the loop, which is really unnecessary, it would look like this:
foreach ($pages as $key => $value) {
if ($key == $allyourbase) {
echo $value['desc'];
}
}
The best solution is to replace the loop with the following code:
if (isset($pages[$allyourbase])) {
echo $pages[$allyourbase]['desc'];
} else {
// error handling
}
If I'm reading this right, echo $key['desc']; should be echo $value['desc'];.

How to get last key with values from array of arrays? PHP

This is what i am currently using
<?php $sidebar = $this->data['sidebar'];
$lastKey = array_pop(array_keys($sidebar));
$sidebar = $this->data['sidebar'][$lastKey]; ?>
<?php foreach($sidebar as $key => $item) { ?>
<li id="<?php echo Sanitizer::escapeId( "pt-$key" ) ?>"<?php
if ($item['active']) { ?> class="active"<?php } ?>><?php echo htmlspecialchars($item['text']) ?></li>
<?php } ?>
This is what i get (http://pastebin.com/t6Y2ZtMF) when i print_r($sidebar);
I want to get the last Array which is Categories and turn it into links.
I am new to php, so my method could be wrong even though it works. I is there a right way to pull the Categories Array or the above code is good as it is?
$lastValue = end($array);
$lastKey = key($array); // current key, which is the last since you called end()
After update:
You don't seem to be needing the key, only the array:
<?php $lastSidebarValue = end($this->data['sidebar']); ?>
<?php foreach ($lastSidebarValue as $key => $item) : ?>
business as usual...
<?php endforeach; ?>
Since you know you want the key 'Categories' though (not the last key), this seems the most logical thing to do:
<?php foreach ($this->data['sidebar']['Categories'] as $key => $item) : ?>
business as usual...
<?php endforeach; ?>
I think the end() function would be a great solution: http://php.net/manual/en/function.end.php
It basically returns the value of the last element in the array being passed to it.
$sidebar = end($sidebar);
If you want to get a key/value pair without popping & pushing the array, set the internal cursor to the end of the array and then use list and each to get the key & value.
// set up your array however you had it
$array = ...;
// move the cursor to the end of the array
end($array);
// use list() and each() to extract your key/value pair
list($key,$val) = each($array);
// $key will now have the last key
// $val will have the last value
perhaps, end:
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
You can use `end()` instead of `array_pop()`. But both works for the **last element** of the array. The only difference is `end()` **points out** the **last element** of the array without effecting it and `array_pop()` **pops** the element off the **end** of array.
Please go through the following links for detail information
end() | array_pop()

Categories