PHP iteration foreach, omitting characters from last iteration - php

I'm tying to iterate through an array, assembling a string to return each time.
My question is how can I omit the comma on the last iteration of the array, or if there is only one element to the array? I'm not sure what this operation would be called as my coding skills are very rudimentary, so I've not had much luck searching for an answer. Even help knowing this basic detail would be much appreciated.
this is the result I'd like:
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' }
Note the lack of a trailing comma.
Below is the php Im using to generate the strings. It will always include a trailing comma which is causing me all sorts of greif.
//snipit
$i = 1;
$a = '';
foreach ($pages as $go)
{
$title = ($go['media_title'] == '') ? ' ' : $go['media_title'];
$caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];
$a .= "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";
$a .= ",\n";
$i++;
return $a;
}
Many thanks for your experience,
orionrush

$a[] = "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";
and use it by
return implode(",\n", $a);

You should really use json_encode().
$data = array();
foreach ($pages as $go) {
$title = ($go['media_title'] == '') ? ' ' : $go['media_title'];
$caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];
$data[] = array(
'image' => BASEURL . GIMGS . '/' . $go['media_file'],
'title' => $title . ', ' . $caption,
'url' => BASEURL . GIMGS . '/' . $go['media_file']
);
}
echo json_encode($data);

foreach ($pages as $go){
$return[] = json_encode($go);
}
return implode(",\n", $return);
do what you like in the foreach, the implode will comma separate the lines like you want

just chop the end off with substr:
return substr($a, 0, -3);

Related

Parsing json with a nested element

does not work with a nested element
the elements of the first level are output, and the nested array with data is not read, as it is possible to get values - id, title and location?
<?php
function removeBomUtf8($s){
if(substr($s,0,3)==chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF'))){
return substr($s,3);
}else{
return $s;
}
}
$url = "https://denden000qwerty.000webhostapp.com/opportunities.json";
$content = file_get_contents($url);
$clean_content = removeBomUtf8($content);
$decoded = json_decode($clean_content);
while ($el_name = current($decoded)) {
// echo 'total = ' . $el_name->total_items . 'current = ' . $el_name->current_page . 'total = ' . $el_name->total_pages . '<br>' ;
echo ' id = ' . $el_name->data[0]->id . ' title = ' . $el_name->data.title . ' location = ' . $el_name->data.location . '<br>' ;
next($decoded);
}
?>
$el_name->data[0]->id is correct
$el_name->data.title is not
you see the difference?
and $decoded is the root (no need to iterate over it) - you want to iterate over the data children
<?php
foreach($decoded->data as $data)
{
$id = (string)$data->id;
$title = (string)$data->title;
$location = (string)$data->location;
echo sprintf('id = %s, title = %s, location = %s<br />', $id, $title, $location);
}

Highcharts Column Range - How to render series data stored in PHP variables?

I have problems when trying to render correctly the Highcharts column range table. I have all the necessary data stored in PHP variables. The problem is that I can't get the table rendered when passing this variables.
If I try to pass direct numeric data, then the table is rendered, so the issue is in the data field.
Here's my code:
<?php
if (!isset($divId)) {
$mt = microtime();
$mt = explode(" ", $mt);
$divId = "stacked_container_" . floor($mt[0] * 100000) . "_" . $mt[1];
}
?>
<div id="<?php echo $divId; ?>" class="col-mx-12"></div>
<?php
$title = $elements['title'];
$resources = $elements['series']['resources'];
$values = $elements['series']['values'];
$resourcesSeries = '';
$valuesMinSeries = '';
$valuesMaxSeries = '';
foreach ($resources as $key => $resource) {
$resourcesSeries .= '"' . $resource . '",';
$valuesMinSeries .= $values[$key][0] . ',';
$valuesMaxSeries .= $values[$key][1] . ',';
}
$globalNav = $view['nav'];
// Transforming strings into array type
$valuesMin = str_split($valuesMinSeries);
$valuesMax = str_split($valuesMaxSeries);
$globalNav->addScriptJS("
$(document).ready(function () {
$('#" . $divId . "').highcharts({
chart: {
type: 'columnrange'
},
title: {
text: '" . $title . "'
},
xAxis: {
categories: [" . $resourcesSeries . "]
},
yAxis: {
title: {
text: 'range'
}
},
series: [{
data: [
[<?php echo $valuesMin[0]?> , <?php echo $valuesMax[0]?> ]
]
}]
});
});
");
?>
In this example I'm trying to display only the first element of $valuesMin and $valuesMax.
The final aim is to render all the data, so I need to implement a foreach too.
You appear to be duplicating your resources array, by calling it as both your $resources variable, and your $values variable:
$resources = $elements['series']['resources'];
$values = $elements['series']['resources'];
Which I will assume should be something like:
$resources = $elements['series']['resources'];
$values = $elements['series']['values'];
I have found a solution to the problem. This is how:
//The result will be in the $data variable
$data = '';
foreach ($resources as $key => $resource) {
$resourcesSeries .= '"' . $resource . '",';
$valuesMinSeries .= $values[$key][0] . ',';
$valuesMaxSeries .= $values[$key][1] . ',';
$data .= "[".values[$key][0]. "," .$values[$key][1]. "],";
}
And in the series field:
series: [{
data: [ " .$data. " ]
}]
Hope this will help!

How to get rid of empty values when adding string in php

I have something like this:
public function options()
{
$out = '';
$docs = $this->getAll();;
foreach($docs as $key => $doc) {
$out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
return $out;
}
It gives me a list of options from the DB, but it also gives me a null value at the top.
if I write it like this:
public function options()
{
//$out = '';
$docs = $this->getAll();;
foreach($docs as $key => $doc) {
$out = '';
$out .= '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
return $out;
}
It doesn't give me the null value but it only returns one value.
$out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
In this line if I don't add an , it gives me an error message, This because I have $out = ''; at the top. Now can you guys give me an idea how can I get all the values from the DB without the empty value at the beginning.
I also have another question , why we use ;; (double semicolon) in this code:
$docs = $this->getAll();;
test $out to see if it has any length, if so add the comma and the line, otherwise just set it to be the line:
$out="";
foreach($docs as $key=>$doc){
if(strlen($out)){
$out.=',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}else{
$out='{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
}
as to your other question, er, you wrote the code, so why did you put a double semi-colon?
This is not the correct way to build JSON. First create an array, and use json_encode() on it.
I'd suggest using an array instead to hold the individual values, and using join to concatenate them together.
public function options()
{
$docs = $this->getAll();
// Create an empty array
$items = array();
foreach($docs as $key => $doc) {
// "Push" an item to the end of the array
$items[] = '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
// Join the contents together
$out = join(",", $items);
return $out;
}
Also, the double semi-colon is completely unnecessary.

Setting variable variables inside a foreach

I am trying to use $value inside the $feed_title variable. And generate all 200 $feed_title variables.
What I am trying to accomplish would look like this:
Feed Url: http://something.com/term/###/feed
Feed Title: Some Title
Where the ### varies from 100-300.
I am using the following code, and getting the urls, but not sure how to get the titles for each feed:
$arr = range(100,300);
foreach($arr as $key=>$value)
{
unset($arr[$key + 1]);
$feed_title = simplexml_load_file('http://www.something.com/term/'
. ??? . '/0/feed');
echo 'Feed URL: <a href="http://www.something.com/term/' . $value
. '/0/feed">http://www.something.com//term/' . $value
. '/0/feed</a><br/> Feed Category: ' . $feed_title->channel[0]->title
. '<br/>';
}
Do I need another loop inside of the foreach? Any help is appreciated.
If you want to get the title of a page, use this function:
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Here's some sample code:
<?php
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
$arr = range(300,305);
foreach($arr as $value)
{
$feed_title = getTitle('http://www.translate.com/portuguese/feed/' . $value);
echo 'Feed URL: http://www.translate.com/portuguese/feed/' . $value . '<br/>
Feed Category: ' . $feed_title . '<br/>';
}
?>
This gets the title from translate.com pages. I just limited the number of pages for faster execution.
Just change the getTitle to your function if you want to get the title from xml.
Instead of using an array created with range, use a for loop as follows:
for($i = 100; $i <= 300; $i++){
$feed = simplexml_load_file('http://www.something.com/term/' . $i . '/0/feed');
echo 'Feed URL: http://www.something.com/term/' . $i . '/0/feed/ <br /> Feed category: ' . $feed->channel[0]->title . '<br/>';
}

php string in to javascript code with comma except last string

I'm using a javascript plugin this is the line which I need help from u
<script type="text/javascript">
$('ul#news').newswidget({ source: ['http://rss.news.yahoo.com/rss/us', 'http://rss.news.yahoo.com/rss/world', 'http://feeds.bbci.co.uk/news/rss.xml'],
I would like to add URL data from MySQL
I'm using it with while loop like this
$('ul#news').newswidget({ source:[<?php
while($rssrow = mysql_fetch_array($rss))
{
echo "'"."$rssrow[rss_name]"."'".",";
}
?>],
It doesn't work properly :(.
I need to get like URL,URL,RUL like this.
that means no comma for the last one
any one please help me
You can actually do that pretty easily by a simple reorganization:
if($rssrow = mysql_fetch_array($rss))
{
echo "'".$rssrow['rss_name']."'";
while($rssrow = mysql_fetch_array($rss))
{
// note no quotes -- they are redundant
// prepend the comma
echo ","."'".$rssrow['rss_name']."'";
}
}
It does make for an extra step for the reader, but it does have the benefit of not needing substring, a new array, or a flag.
You could just build the string and remove the last comma:
$result = '';
while($rssrow = mysql_fetch_array($rss))
{
$result .= "'"."$rssrow[rss_name]"."'".",";
}
echo ($result != '') ? substr($result, 0, -1) : "''";
OR use implode():
$result = array();
while($rssrow = mysql_fetch_array($rss))
{
$result[] = $rssrow[rss_name];
}
echo "'" . implode($result, "','") . "'";
(both of these methods will output '' if the result set is empty.)
$urls = "";
while($rssrow = mysql_fetch_array($rss))
{
$urls.= "'$rssrow[rss_name]',";
}
echo substr($urls, 0, -1);
I wonder why no comment points out that you should definitely escape your output. If an entry contains a ', all solutions aside from Dmitry F’s first will break badly.
$('ul#news').newswidget({ source:[<?php
$arr = array();
while($rssrow = mysql_fetch_array($rss))
{
$arr[] = '"' . str_replace('"', '\"', $rssrow['rss_name']) . '"';
}
echo implode(',', $arr);
?>],
here is a little bit different approach:
<?php
$news = array(
'source' => array(
'http://example.com',
'http://example.com'
)
);
$news_json = json_encode($news);
?>
<script>
$('ul#news').newswidget(<?php echo $news_json; ?>);
</script>
another variation:
$url = array();
while($rssrow = mysql_fetch_array($rss))
{
$url[] = '"' . $rssrow['rss_name'] . '"';
}
echo implode(',', $url);

Categories