I'm working on a script that will retrieve API information of the 'near earth objects' from NASA's website. User selects date, api grabs the information and displays it. How do I fix the foreach in this script? would appreciate some help with this.
$jsonAsteroids = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($jsonAsteroids, true);
echo "<h4>Retrieving the first element (i.e. \"links\") of the JSON structure</h4>";
var_dump( $data["links"]);
echo "<h4>Retrieving the first element (i.e. \"next\") inside the \"links\" element</h4>";
echo( $data["links"]["next"]);
You were very close. Your main issue was that you used json_decode(..., true); which gives you an array, but then used the object->property syntax instead of object['property']. My suggestion is to use json_decode without the 2nd argument in this case.
Finally, your 2nd foreach was malformed.
<?php
$result = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($result);
foreach ($data->near_earth_objects as $date => $objects) {
echo "<p>" . count($objects) . " objects detected on $date</p>";
echo "<ol>";
foreach ($objects as $object) {
echo "<li>" . $object->name . " <a href='" . $object->nasa_jpl_url . "'>" . $object->nasa_jpl_url . "</a><br>";
echo "Diameter of the object: " . $object->estimated_diameter->meters->estimated_diameter_min . "-" . $object->estimated_diameter->meters->estimated_diameter_max . " metres<br>";
echo "<ul>";
foreach ($object->close_approach_data as $close_approach) {
echo "<li>Close approach: " . $close_approach->close_approach_date . " traveling at a velocity of " . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "missing " . $close_approach->orbiting_body . " by " . $close_approach->miss_distance->kilometers . " km</li> ";
}
echo "</ul>";
}
echo "</ol>";
}
I am using a plugin for WordPRess called Easy Bootstrap Shortcodes to use Booystrap CSS within wordpress posts. Tabs are one feature I use a lot and when I use the tabs short code, it throws the following error:
Notice: Undefined index: tabs in /home/onedirec/public_html/tester/wp-content/plugins/easy-bootstrap-shortcodes/shortcode/tabs/plugin_shortcode.php on line 38
What's weird is that the tabs and all the information following is rendered apart from an indent that shouldn;t be there. You can see this in action here: http://onedirectionconnection.com/tester/?projects=take-me-home-tour
If anyone could help me figure out what the issue is, it would be greatly appreciated. Here's the code that's causing the error:
<?php
/* * *********************************************************
* jQuery UI Tabs
* ********************************************************* */
$_oscitas_tabs = array();
function osc_theme_tabs($params, $content = null) {
global $_oscitas_tabs;
extract(shortcode_atts(array(
'id' => count($_oscitas_tabs),
'class' => ''
), $params));
$_oscitas_tabs[$id] = array();
do_shortcode($content);
$scontent = '<ul class="nav nav-tabs " id="oscitas-tabs-' . $id . '">' . implode('', $_oscitas_tabs[$id]['tabs']) . '</ul><div
class="tab-content">' . implode('', $_oscitas_tabs[$id]['panes']) . '</div>';
if (trim($scontent) != "") {
$output = '<div class="' . $class . '">' . $scontent;
$output .= '</div>';
return $output;
} else {
return "";
}
}
add_shortcode('tabs', 'osc_theme_tabs');
function osc_theme_tab($params, $content = null) {
global $_oscitas_tabs;
extract(shortcode_atts(array(
'title' => 'title',
'active' => '',
), $params));
$index = count($_oscitas_tabs) - 1;
$pane_id = 'pane-' . $index . '-' . count($_oscitas_tabs[$index]['tabs']);
$_oscitas_tabs[$index]['tabs'][] = '<li class="' . $active . '"><a href="#' . $pane_id . '" data-toggle="tab">' . $title
. '</a></li>';
$_oscitas_tabs[$index]['panes'][] = '<div class="tab-pane ' . $active . '" id="'
. $pane_id . '">'
. do_shortcode
(trim($content)) . '</div>';
}
add_shortcode('tab', 'osc_theme_tab');
And here is line 38 on its own:
$pane_id = 'pane-' . $index . '-' . count($_oscitas_tabs[$index]['tabs']);
I know very little about PHP so if anyone can help me spot the error here, it would be greatly appreciated.
Well I'll just post the answer here since it worked in the comments.
Add this line just before line 38:
$_oscitas_tabs[$index]['tabs'] = array();
Right above this line:
$pane_id = 'pane-' . $index . '-' . count($_oscitas_tabs[$index]['tabs']);
That should stop the PHP notice from appearing.
You could try adding a # right before count()
$pane_id = 'pane-' . $index . '-' . #count($_oscitas_tabs[$index]['tabs']);
It keeps PHP from complaining.
I am modifying a wordpress function. I have the following code:
$output .= $r['link_before'] . '<ul><li class="bbp-forum-info">' . $title . '</li>' . $counts . '<li class="bbp-forum-freshness">' . $subfresh . '</li></ul>' . $r['link_after'];
And I need the ul tag to look like this:
<ul id="bbp-forum-<?php bbp_forum_id(); ?>" <?php bbp_forum_class(); ?>>
However, I don't know how to add those php tags inside of that code. I have tried it in a number of different ways, but haven't been able to get it to work. Any advice?
use the . to concatenate strings:
$c='a'.'b';
echo $c //outputs 'ab'
knowing that, just:
$output .= $r['link_before'] . '<ul id="bbp-forum-'.bbp_forum_id().'" '.bbp_forum_class().'><li class="bbp-forum-info">' . $title . '</li>' . $counts . '<li class="bbp-forum-freshness">' . $subfresh . '</li></ul>' . $r['link_after'];
if you are adding it correctly
$output .= $r['link_before'] . '<ul id="bbp-forum-<?php bbp_forum_id(); ?>" <?php bbp_forum_class(); ?>><li class="bbp-forum-info">' . $title . '</li>' . $counts . '<li class="bbp-forum-freshness">' . $subfresh . '</li></ul>' . $r['link_after'];
This is hard to answer without further knowlege of the system.
ensure bbp_forum_class(); echoes something along the lines of class="foo"
if that isnt your issue, your style may be overridden by the li class. ensure you dont have conflicting css!
This is tailing off my other question which was successfully answered: stackoverflow.com/questions/8597929/need-to-create-li-with-list-of-different-links-using-php-explode-method
so now I have this:
<?php
$separator1 = "\n";
$separator2 = ":";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links) = explode($separator2, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
and that, using the following in a textarea which is defined to "my_custom_output":
text1:text1-page-url
text2:new-text2-page
text3:different-page-text3
and the result is
text1
text2
text3
which are successfully linked and styled. (i didnt make them links because stackoverflow doesn't let me post more than two links because i only have 3 rep).
So my next and final desired task is to do this:
text1
description 1
text2
description 2
text3
description 3
where the text1 etc are linked like before but the descriptions are not linked.
So I will do my best, right here in stackoverflow, to try it. However, I expect I will need some help. Let's go:
<?php
$separator1 = "\n";
$separator2 = ":";
$separator3 = ";";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links) = explode($separator2, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
and to use the following in the textarea which is is defined to "my_custom_output":
text1:text1-page-url;Text1 Description
text2:new-text2-page;Description For Text2
text3:different-page-text3;A Text3 Description
and I need the output to be:
text1
Text1 Description
text2
Description For Text2
..etc
I don't know if semicolon will work, but I can't use a space (\s) because there are spaces in the description. I am open to suggestions.
====================================================
MY NEWEST TRY:
<?php
$separator1 = "\n";
$separator2 = ":";
$separator3 = ";";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
$itemarray = explode($separator2, trim($item));
$item_text = $itemarray[0];
list($item_links, $item_desc) = explode($separator3,$itemarray[1]);
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
IT WORKS!!! =D
Not sure if I understand this well enough (I'm not sure what get_custom_field() gets you - can't find that as a regular PHP function), but when you explode an item that has multiple instances of the delimiter, you'll get multiple arrays.
So:
$textarea = "text1:text1-page-url;Text1 Description";
$data = explode(':',$textarea);
// at this point $data[0] will contain "text1", while $data[1] contains text1-page-url;Text1 Description"
$descarray = explode(';',$data[1]);
// then $descarray[0] contains "text1-page-url" and $descarray[1] contains "Text1 Description" so you can echo this out however you like.
To work with your code..
Assume each $item is each row at this point, like this:
$item = "text1:text1-page-url;Text1 Description";
Then this will do the trick:
foreach ($array as $item) {
$itemarray = explode($separator2, trim($item));
$item_text = $itemarray[0];
list($item_links, $item_desc) = explode(';',$itemarray[1]);
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
I'd slightly optimize the algorithm as there is no need for second explode(). Just separate substrings within one row with the same separators (and don't forget to escape that separator inside all your data):
<?php
$row_separator = "\n";
$line_separator = ":";
$textarea = get_custom_field('my_custom_output');
$array = explode($row_separator, $textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links, $item_desc) = explode($line_separator, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
And here is the data format I suggest to use (separate all fields by :)
text1:text1-page-url:Text1 Description
text2:new-text2-page:Description For Text2
text3:different-page-text3:A Text3 Description
I want to be able to parse the following json data. It was constructed from a php array using jsonencode. I've added the json below to help you understand it. I'd like to be able to display the json in a bulleted form. It show two records with associated category array and tags array. Im open to using any libraries to help.
{"0":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"908","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Liverpool Football Club","post_content":"Content goes here...","post_name":"liverpoolfc","guid":"http://www.liverpoolfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0},"1":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"907","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Everton Football Club","post_content":"Content goes here","post_name":"evertonfc","guid":"http://www.evertonfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0}}
I want to be able to parse it and display like this.
Liverpool Football Club
Content goes
here
Categories
Football Club
Tags
England
EPL
UPDATE: Sorry i need to parse it in javascript.
Try this:
$json = '{"0":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"908","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Liverpool Football Club","post_content":"Content goes here...","post_name":"liverpoolfc","guid":"http://www.liverpoolfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0},"1":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"907","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Everton Football Club","post_content":"Content goes here","post_name":"evertonfc","guid":"http://www.evertonfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0}}';
$array = json_decode($json, true);
foreach ($array as $item) {
echo '<ul>' . PHP_EOL;
echo '<li>' . $item['post_title'] . '</li>' . PHP_EOL;
echo '<li>' . $item['post_content'] . '</li>' . PHP_EOL;
/* Display Categories */
echo '<li>Categories' . PHP_EOL;
echo '<ul>' . PHP_EOL;
if (!empty($item['categories'])) {
foreach ($item['categories'] as $category) {
echo '<li>' . $category['name'] . '</li>' . PHP_EOL;
}
} else {
echo '<li>No Categories Available</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
/* Display Tags */
echo '<li>Tags' . PHP_EOL;
echo '<ul>' . PHP_EOL;
if (!empty($item['tags'])) {
foreach ($item['tags'] as $tag) {
echo '<li>' . $tag['name'] . '</li>' . PHP_EOL;
}
} else {
echo '<li>No Tags Available</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
echo '</ul>' . PHP_EOL;
}
UPDATE Are you asking on how to do this in PHP or in Javascript/jQuery? You didn't quite explain what you were doing with it.
UPDATE Here it is using Javascript/jQuery: http://jsfiddle.net/wgjjR/
//<div id="container"></div>
//var json = {}; // this is your JSON object
var container = $('#container'), html = [];
for (var key in json) {
var item = json[key];
html.push('<ul>');
html.push('<li>' + item.post_title + '</li>');
html.push('<li>' + item.post_content + '</li>');
html.push('<li>Categories<ul>');
for (var cat in item.categories) {
cat = item.categories[cat];
html.push('<li>' + cat.name + '</li>');
}
html.push('</ul></li>');
html.push('<li>Tags<ul>');
for (var tag in item.tags) {
tag = item.tags[tag];
html.push('<li>' + tag.name + '</li>');
}
html.push('</ul></li>');
html.push('</ul>');
}
$json = json_decode($inputJson, true);
foreach($json as $key => $value)
{
// do somethig
}
Use json_decode
$json = json_decode($some_json, true);
$element1 = $json["item"]["element1"];
$element2 = $json["item"]["element2"];
Repeat to extract all the values you require.