Output All Currency Values using PHP - php

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>

Related

How to convert resultset to nested unordered list and hide sublist items with a value of 0?

I am trying to display the below table value in list and sub-list.
and here is my for loop to display
$sql ="SELECT *FROM objectives";
$result = $conn->query($sql);
$categories = array();
foreach ($result as $result) {
$category = $result['content'];
$categories[$category][] = $result['sub_content'];
}
?>
<ul>
<?php foreach ($categories as $category => $subcategories): ?>
<li>
<?php echo $category; ?>
<ul>
<?php foreach ($subcategories as $subcategory):?>
<li><?php echo $subcategory; ?></li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
</ul>
The data is displayed in list and with sub list. I don't want to display the 0 value in the sub-list.
Everything is fine except the display of 0 in sub-list. Please advise.
try this if you just don't want to display 0
<?php echo ($subcategory != '0')? '<li>'.$test.'</li>' : ''; ?>
and if you don't want to store in array then put this if condition
foreach ($result as $result) {
$category = $result['content'];
if($result['sub_content'] != '0'){
$categories[$category][] = $result['sub_content'];
}
}
Simply implementing echo ($subcategory != '0')? '<li>'.$test.'</li>' : ''; will result in needless markup in the dom. Specifically, you will have empty <ul></ul> tags as nested lists where only a single row containing $subcategory is 0. (Demonstration) These extra bits of markup may cause funky side-effects when css/styling is applied.
Further refinements are advisable as a matter of best practice:
When querying the database, only SELECT the columns that you specifically require for your task.
Add stability to your process by using an ORDER BY clause that will group the rows by content and possibly sort sub_content
Never use more loops than necessary. This task can be (and therefore, theoretically, should be) performed in a single loop.
Recommended Code: (Demo)
$result = $conn->query("SELECT content, sub_content FROM objectives");
$category = null;
$output = '';
foreach ($result as $row) {
if ($category !== $row['content']) { // new parent
if ($category !== null) { // not first iteration
$output .= "<li>$category"; // print parent
if ($sublist) {
$output .= "<ul>$sublist</ul>"; // print all children
}
$output .= "</li>";
}
$category = $row['content']; // overwrite $category
$sublist = ''; // reset sublist
}
if ($row['sub_content'] !== '0'){ // filter row
$sublist .= "<li>{$row['sub_content']}</li>";
}
}
if ($result) { // in case the resultset is empty
echo "<ul>";
echo $output; // print stored markup
echo "<li>$category"; // print last parent
if ($sublist) {
echo "<ul>$sublist</ul>"; // print all children from last parent
}
echo "</li>";
echo "</ul>";
}
Source Code Output:
<ul>
<li>Demonstrate where to find the following documentation:
<ul>
<li>Operating and Safety Strategy</li>
</ul>
</li>
<li>Explain the different turbine main operating states:
<ul>
<li>Power Production</li>
<li>Idle</li>
<li>Stop</li>
</ul>
</li>
<li>Explain how to recognise the current operating mode on the display of the operating panel</li>
<li>Explain the subsystem operating modes:
<ul>
<li>Stop</li>
<li>Manual</li>
</ul>
</li>
<li>Explain the difference between local and remote point of operation</li>
<li>Explain that only one point of operation can be active at a time</li>
</ul>
Rendered Output: (courtesy of phptester.net)

Special treatment to part of PHP array

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

How to ACF list label not value

Im using ACF repeater to generate results form a list, which is all working fine. But, rather than display the list value, I want to display the list label.
Here is the code:
<ul class="notifications-content">
<?php while(has_sub_field('notification')):
$house = get_sub_field('house');
$year = get_sub_field('year');
$date = DateTime::createFromFormat('Ymd', get_sub_field('date'));
$newDate = date("D j F", strtotime($date->format('d-m-Y')));
?>
<li class="<?php echo safe_url($house); ?> <?php echo $year; ?>">
<h2 class="black"><?php echo str_replace($replace, '', get_sub_field('message')); ?></h2>
<h3 class="interstatebold white uppercase"><?php echo $house; echo $year ? ", $year" : ''; echo ' | '.$newDate; ?></h3>
<?php echo get_sub_field('urgent') ? '<div class="circle"></div>' : ''; ?>
</li>
<?php endwhile; ?>
</ul>
How do I get the label?
Take a look at this official documentation about get_field_object
There is a usage example in the bottom:
Get a field object and display it with it's value
$field_name = "text_field";
$field = get_field_object($field_name);
echo $field['label'] . ': ' . $field['value'];
You can use this in your repeater to grab that field_object you want and display the label.
Instead of using has sub field, use get_field('platforms'). Put respective repeater field name in place of 'platforms.' Platforms is the name of repeater field.
By using foreach loop with key=>value pair, you get key as well as value.
Try using following code.
$platforms = get_field('platforms');
foreach( $platforms as $val ){
foreach($val as $key=>$v){
echo $key.'=>'.$v.'<br>';
}
}
You can use it the same way you would call the field values by passing it through these functions (add to functions.php):
function get_field_label($slug) {
$field = get_field_object($slug);
return $field['label'];
}
Usage:
<?php echo get_field_label('field-slug'); ?>
function the_field_label($slug) {
$field = get_field_object($slug);
echo $field['label'];
}
Usage:
<?php the_field_label('field-slug'); ?>

str_replace in model or the view?

Model
function Show_all_products()
{
return $this->db->get('printer')->result();
}
View
The table contents is being echoed in a loop
$i = -1;
echo '<ul class="products">'; foreach($products as $product) :
if($i % 11 == 10) echo '</ul><ul class="products">';
?>
<li><?php echo $product->name; ?> </li>
<?php
$i += 1;
endforeach;
echo "</ul>";
The product names are saved as Something_Something_Blah I cannot modify the product names as they are configured to show clean URL's and Breadcrumbs.
The issue is that the links in this view show as Something_Something_Blah
I tried to do a str_replace as $product = str_replace('_',' ', $product); However this isn't working.
How do i strip the '_' and insert \s ?
I see you have <?php echo $product->name; ?> which would mean $product is an object.
So you should call str_replace('_', ' ', $product->name);
<?php
$i = -1;
echo '<ul class="products">'; foreach($products as $product) :
$product->name = str_replace('_',' ', $product->name);
if($i % 11 == 10) echo '</ul><ul class="products">';
?>
<li><?php echo $product->name; ?> </li>
<?php
$i += 1;
endforeach;
echo "</ul>";
?>
str_replace must be called from within the foreach or an error will be returned. That was my mistake.
As per PHP documentation, str_replace() accepts a string or array as it's third argument. You are passing it an object. You should pass $product->name to it.
Furthermore, please strive to embed PHP in your HTML and not HTML in your PHP. You're going to find yourself echoing everything. You don't need to manually create the $i iterator either, because the foreach loop will create one for you, provided you use the foreach($x as $key => $val) syntax. You can lose the <?php echo $var;?> for <?= $var;?> too, AND concatenate with the . symbol:
<ul class="products">
<? foreach($products as $pK => $pV):?>
<? if($pK % 11 == 10):?></ul><ul class="products"><? endif;?>
<li>
<?= $pV->name;?>
</li>
<? endforeach;?>
</ul>

Turning a single string into a list of separate links

I have a field called links that accepts a list of URLs separated by a comma, e.g. 'www.bbc.co.uk, www.itv.co.uk'
When I then output the contents of the field, I wrap it in code like this:
<li><a href='http://<?php echo htmlout($name['links']); ?>'><?php echo htmlout($name['links']); ?></a></li>
This works fine when a single link is added but when there is more then one, then it causes problems.
If for instance I have two links, one is www.bbc.co.uk and one is www.itv.co.uk and then I hover over the link (it is a single link of instead of two), it shows as:
http://www.ts.co.uk%2C%20www.bbc.co.uk/
Now I'm thinking that because they are separated by commas, there may be some way to use this as a hook to split the URLs up but I am not sure if this is possible.
Any help is appreciated. Thanks
EDIT BELOW
Added some code below as I already have an array. Can I have an array within an array? Should I in this case? Where should I drop the suggested code in?
INDEX.PHP (Controller)
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try
{
$sql = "SELECT player.id, player.name AS name, age, position, height, weight, GROUP_CONCAT(distinct previousclubs.name) previousclubs,
satscore, gpa, GROUP_CONCAT(distinct link) link, email
FROM player INNER JOIN playerpreviousclubs
ON player.id = playerid
INNER JOIN previousclubs
ON previousclubid = previousclubs.id
INNER JOIN links
ON links.playerid = player.id
WHERE email = '$username'";
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching details: ' . $e->getMessage();
include 'error.html.php';
exit();
}
foreach ($result as $row)
{
$names[] = array(
'id' => $row['id'],
'name' => $row['name'],
'age' => $row['age'],
'position' => $row['position'],
'height' => $row['height'],
'weight' => $row['weight'],
'previousclubs' => $row['previousclubs'],
'satscore' => $row['satscore'],
'gpa' => $row['gpa'],
'links' => $row['link'],
'email' => $row['email']
);
}
include 'profiles.html.php';
And my template looks like this currently:
PROFILES.HTML.PHP
<p>Welcome <?php echo $row['name'] ?> . Below are your profile details:</p>
<?php foreach ($names as $name): ?>
<form action="" method="post">
<ol>
<li class="listleft">Name:</li>
<li><?php echo htmlout($name['name']); ?></li>
<li class="listleft">Age:</li>
<li><?php echo htmlout($name['age']); ?></li>
<li class="listleft">Position:</li>
<li><?php echo htmlout($name['position']); ?></li>
<li class="listleft">Height:</li>
<li><?php echo htmlout($name['height']); ?></li>
<li class="listleft">Weight:</li>
<li><?php echo htmlout($name['weight']); ?></li>
<li class="listleft">Previous Clubs:</li>
<li><?php echo htmlout($name['previousclubs']); ?></li>
<li class="listleft">GPA:</li>
<li><?php echo htmlout($name['satscore']); ?></li>
<li class="listleft">SAT Score:</li>
<li><?php echo htmlout($name['gpa']); ?></li>
<li class="listleft">Links:</li>
<li><a href='http://<?php echo htmlout($name['links']); ?>'><?php echo htmlout($name['links']); ?></a></li>
</ol>
</form>
<?php endforeach; ?>
$links = explode(',', $links);
foreach($links as $link) {
echo '<li>'.$link.'</li>';
}
You'll need to explode them, then loop through them.
$links = explode(',', $name['links']);
Then in your view:
foreach ($links as $link) {
echo '<li>'.$link.'</li>';
}
You can easily split string using explode function:
// split string by comma, returns array
$linksArray = explode(',', $links);
foreach($linksArray as $link) {
echo $link; // print each link etc
}
You'd be better to explode the string into an array, then loop around the array to output the data. Personally, I find arrays much easier to work with than a string. For example:
$links = explode(',', $links);
foreach($links as $link) {
?>
<li><?php echo htmlout($link); ?></li>
<?php
}

Categories