I want to add a special class to the a certain entry of an array value. What do I need to add to that value in the array to give it's 'li' a special class?
I have an array like this:
"notes" => [
"$100.00 Credit to Use at Any of",
"the Domestic Bliss Spa Locations",
"$100.00 Value",
"Another list item",
"yet another list item"
]
And I loop through these to spit out html like this:
<?php foreach ($slide['notes'] as $note): ?>
<li><?= $note; ?></li>
<?php endforeach; ?>
I want the value $100.00 Value to have a special class.
Try this:
<?php foreach ($slide['notes'] as $note): ?>
<li <?php if ($note == "$100.00 Value") echo "class='specialClass'" ?>><?= $note; ?></li>
<?php endforeach; ?>
Here you can check for multiple values like this way as :
<?php
foreach ($slide['notes'] as $note) {
$values = array("$300.00", "$200.00", "$100.00", "$55.00");
if (in_array($note, $values))
{
echo "<li class='special_class_name'>$note</li>";
} else {
echo "<li>$note</li>";
}
}
?>
You can use strpos to check if $note contains $100.00 Value and use the ternary operator, like this:
<?php
foreach ($slide['notes'] as $note){
echo (strpos($note, '$100.00 Value') !== false) ? "<li class='someClass'>{$note}</li>" : "<li>{$note}</li>";
}
Ideone Demo
Related
i want to call sidebar menu items from database, but when i put the items from database to the which is i put in $menu, it returns error
<?php
$a=0;
foreach ($menu as $m ) {
$data[$a]=$m->menu_name;
// $menu .="<li class='active'><a href='#'><em class='fa fa-dashboard'> </em> ".$m->menu_name."</a></li>";
$menu.="<li><a href ='#'>".$data[$a]."</a></li>";
// echo $m->menu_name;
$a++;
}
?>
<?php echo $menu; ?>
I dont know what's wrong, any help will appreciate. Thanks
Variable name conflict in your case. You have $menu variable which is an array then again you are assigning the menu li element to same variable. change variable name for li element like
<?php
$a=0;
$menu1 = '';
foreach ($menu as $m ) {
$data[$a]=$m->menu_name;
$menu1.="<li><a href ='#'>".$data[$a]."</a></li>";
// $menu2.="<li><a href ='#'>".$m->menu_name;."</a></li>";
$a++;
}
?>
<?php echo $menu1; ?>
IT help to convert your data in array to encode string.
Code:
$menu_title= json_encode($menu);
<?php echo $menu_title; ?>
Or
<?php
echo implode("",$memu);
?>
I am trying to utilize the Bitcoin Charts API to display bitcoin value in all currencies as list items.
Currently I am repeating this PHP snippet in each list item:
<li class="myClass">
<?php
foreach(json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json")) as $item)
if($item->symbol == 'localbtcPLN') break;
printf("\t%s\nPLN", $item->avg);
?>
</li>
How can I simplify this so that the code is only calling the JSON file once?
Thanks for your help.
As per Vishal's assistance, I tried this:
<?php $all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
foreach ($all_data as $data)
{
?><li class="pure-menu-item pure-menu-disabled">
<?php
echo $data['ask'];//use the keyname to get the value
echo ' ';
echo $data['currency'];
?>
</li>
<?php
}
?>
However, it is outputting too much data, including empty values.
Using what I've learned from Florian and Vishal, I have attempted the following snippet, which outputted the data perfectly with the caveat of some duplicated currencies.
<?php $all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
foreach ($all_data as $data)
{
if(trim($data['avg']) != "")//check if value not empty
{
?><li class="pure-menu-item pure-menu-disabled">
<?php
echo $data['avg']; //use the keyname to get the value
echo ' ';
echo $data['currency'];
?>
</li>
<?php
}
}
?>
you can run a foreach loop
<ol>
<?php $all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
foreach ($all_data as $data)
{
if(trim($data['currency']) != "")//check if value not empty
{
?><li>
<?php echo $data['bid'];//use the keyname to get the value ?>
</li>
<?php
}
}
?>
</ol>
I think you want to show values in a certain order.
First, store the result of json_decode() in an array like #Vishal Wadhawan said.
$all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
Next, make a new array where you will store only symbol and avg:
$myvalues = array();
foreach ($all_data as $data)
{
$myvalues[$data['symbol']] = $data['avg'];
}
After that, you can use $myvalues to display avg like that:
<li class="myClass">
<?php echo $myvalues['localbtcPLN'] . ' PLN'; ?>
</li>
You can also store the 'currency' value:
$myvalues[$data['symbol']] = array(
'avg' => $data['avg'],
'currency' => $data['currency'],
);
And access it with:
<li class="myClass">
<?php echo $myvalues['localbtcPLN']['avg'] . ' ' . $myvalues['localbtcPLN']['currency']; ?>
</li>
For some reason my code is an array one minute and not the next. I'm just learning php and I can't figure this out. I've used this page to figure most of this out: How to add two Google charts on the one page?
My code is also used on a page that shows the data as a table. On that page it works fine....but for some reason I'm getting Invalid argument supplied for foreach() on the pie charts page...and it's saying it's not an array. I'm not sure how to go about fixing this.
The url I'm using is ?action=scores&data=pie so it should list all of the universities in "get_universities()" (there's 3 there).
Can anyone help please?
The switch:
// Showing scores
case 'scores':
// Grab the Uni ID and use the appropriate query
if (isset($_GET['uni_id']))
{
$uni_id = $_GET['uni_id'];
$uni = get_university($uni_id);
}
else
{
$uni = get_universities();
}
// We have to display this data according to the request
if (isset($_GET['data']))
{
$data = $_GET['data'];
}
else
{
$data = "table";
}
// Display the data accordingly
include (root . '/view/' . $data . '_view.php');
break;
The pie graphs:
// Create the data table.
<?php foreach ($uni as $uni) : ?>
var data<?php echo $uni['university_id']; ?> = new google.visualization.DataTable();
data<?php echo $uni['university_id']; ?>.addColumn('string', 'Area');
data<?php echo $uni['university_id']; ?>.addColumn('number', 'Score');
data<?php echo $uni['university_id']; ?>.addRows([
['Teaching', <?php echo $uni['teaching_score']; ?>],
['Intl Outlook', <?php echo $uni['int_outlook_score']; ?>],
['Industry Income', <?php echo $uni['ind_income_score']; ?>],
['Research', <?php echo $uni['research_score']; ?>],
['Citations', <?php echo $uni['citations_score']; ?>]
]);
<?php endforeach ?>
// Set chart options
<?php foreach ($uni as $uni) : ?>
var options<?php echo $uni['university_id']; ?> = {'title':'<?php echo $uni['university_name']; ?> Scores',
'width':400,
'height':300};
<?php endforeach ?>
// Instantiate and draw our chart, passing in some options.
<?php foreach ($uni as $uni) : ?>
var chart<?php echo $uni['university_id']; ?> = new google.visualization.PieChart(document.getElementById('chart_div<?php echo $uni['university_id']; ?>'));
chart.draw(data<?php echo $uni['university_id']; ?>, options<?php echo $uni['university_id']; ?>);
<?php endforeach ?>
The table view (which works):
<?php foreach ($uni as $uni) : ?>
<td>
<a href="?uni=<?php echo $uni['university_id']; ?>">
<?php echo $uni['university_name']; ?>
</a>
</td>
<etc>
The problem is with your foreach statement:
foreach ($uni as $uni) :
Here you override the $uni variable. Use different names for the collection and item, eg:
foreach ($uni as $theUni) :
// also change instances of $uni below
EDIT
The above is wrong. The parsing of the first parameter of foreach happens only once so in that foreach it won't be a problem. However a foreach is not a new scope, so if you plan to reuse the array variable, you need to choose a different name as the iterator so it won't get overridden.
$a = array(); // $a is array
foreach ($a as $a) {
// $a is element of original $a
}
// $a is the last element of the original $a array
foreach ($a as $a) // Fail, since $a is not an array anymore
I got below code
<?php foreach ( $resultsb as $optionb ) : ?>
<option value="<?php echo $optionb->bID; ?>"><?php echo $optionb->book;?></option>
<?php endforeach; ?>
i know how the foreach is working here but i didn't get the : after the php statement what does the : do after the foreach statement
<?php foreach($resultsb as $optionb) : ?>
...
<?php endforeach; ?>
is nothing else then:
<?php foreach($resultsb as $optionb) { ?>
...
<?php } ?>
IMO it enhances the readability in files with a lot of html/xml etc.
Try like This
$a = array(1, 2, 3, 17);
foreach ($a as $v) {
echo "Current value of \$a: $v.\n";
}
Your code is true. You must check your array. Error not related to ":". It related to your $resultsb.
I currently have some VERY long winded code for the menu I use on my site.
My website
It's almost 2000 lines long lol. I think I may be able to use a switch but I've tried and cannot implement it to work properly.
On each menu when you click a button it stays highlighted, telling the user that they are on that page. The only way I could get this to work was like so...
if($subject == 'art') {
echo '<div id="spacer2"><br></div>';
echo '<div class="idName2" id="menu2">';
echo 'All';
echo '<div id="spacer2"><br></div>';
echo '</div>';
echo '<div class="idName3" id="menu3">';
echo 'Art';
echo '</div>';
echo '<div class="idName2" id="menu2">';
echo 'Biology';
echo 'English';
echo 'Chemistry';
echo 'Mathematics';
echo 'History';
echo 'Religion';
echo 'Geography';
echo 'Music';
echo 'Philosophy';
echo 'Psychology';
echo 'Economics';
echo 'Sociology';
echo 'Technology';
echo 'Electronics';
echo 'Food';
echo 'Law';
echo 'Politics';
echo '</div>';
}
elseif($subject == 'biology') {
and then there's however many 'elseifs' as there are menu items, which ends up totalling to 2000 lines of code which is obviously very inefficient and it also makes it unbelievably time consuming to change anything... can someone point me in the right direction in what I need to do please!
Navigation is always a pain. Here is a simple solution that might help.
Put everything in an array, like this:
$menu = array(
'All' => '/browse ...',
'Art' => '/browse ... art',
'Biology' => '/browse ... biology',
// etc.
)
Then, you can build all the links based on the current subject:
$subject = 'Art';
foreach ($menu as $title => $url) {
if ($title == $subject) {
echo "<b>$title</b><br>\n";
} else {
echo "$title<br>\n";
}
}
This is a rather simplistic solution, but it can be extended to create a more complicated menus structure.
Another solution you could look at is Zend_Navigation.
http://framework.zend.com/manual/en/zend.navigation.introduction.html
What about something like:
$subjects = array('art', 'biology', 'english', 'chemistry' /*, etc */);
foreach ($subjects as $current_subject)
{
if ($current_subject == $subject)
{
//write it the id="menu3" way
}
else
{
//write it another way
}
}
You can transform 'biology' to 'Biology' using the ucfirst function.
Also note that there can't be two or more elements with the same ID (menu2 in your case).
You should use an array to represent your menus. Even better, you could place it in a resource file (xml would be preferable), but explaining that exceeds the scope of this answer (nonetheless, you should look into it). Using an external resource for the menu has the added benefit that you can change your menu structure without modifying any code.
Sticking to the simple approach, this is how you should represent your menu without an external resource:
$menus = array('Art', 'Biology', 'English', ...);
You can generate the "A"-"Z" submenus with a simple range command: range('A', 'Z')
So your code echoing the menus would be something like:
<?php
$current_letter = $_REQUEST['letter'];
$current_menu = $_REQUEST['menu'];
$letters = range('A', 'Z');
foreach($letters as $letter) :
$class = $current_letter == $letter ? 'class="active"' : '';
?>
<a <?php echo $class; ?> href="browse.php?letter=<?php echo $letter; ?>&menu=<?php echo $current_menu; ?>&listtype=<?php echo $listtype"><?php echo $letter; ?></a>
<?php endforeach; ?>
This displays the top menubar (A-Z links). For the side menu, here is how to display your categories:
<?php
foreach($menus as $menu) :
$class = $current_menu == $menu ? 'class="active"' : '';
?>
<a <?php echo $class; ?> href="browse.php?letter=<?php echo $current_letter; ?>&menu=<?php echo $menu; ?>&listtype=<?php echo $listtype"><?php echo $menu; ?></a>
<?php endforeach; ?>
Haven'tested it, but apart from possible typos this approach should work for you.
Btw, please don't throw things at me for not validating input and using $_REQUEST directly. It should be done, but that is a whole other topic.