This may be a stupid question, so please go easy on me if so.
I have a range of queries (MySQL) returning multidimensional arrays.
I then use these array items to populate variables in a string in a foreach loop.
I then need this string to populate a javascript graph so the format of the data wants to be perfect. this idea works with 1 multidimensional array.
However. To do multiple graphs (e.g comparison line graph) I need to express all the data in the same row.
So what I need to be able to do is if possible merge row to row of the array, rather than add it to the end.
Ill show you my working:
foreach ($graph_month as $month) :
$first .= ' { year: "'.$month['month'].'",';
endforeach;
foreach ($graph_data1 as $data) :
$second1 .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
foreach ($graph_data2 as $data) :
$second2 .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
foreach ($graph_data3 as $data) :
$second3 .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
foreach ($graph_data4 as $data) :
$second4 .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
foreach ($graph_data5 as $data) :
$second5 .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
So each of the foreach's is populating a little section of the javascript required, however I need to be able to concatenate all these rows on the right of each other.
e.g
a foreach that can produce:
$first.$second1.$second2.$second3.$second4.$second5
Is this possible, would it be possible to add [i] and [i++] to each variable.
To start with, you could eliminate the extra foreach lines by generating variables like this:
foreach ($graph_month as $month):
for ($i = 1; $i <=5; $i++) {
//$graph_data$i becomes $graph_data1, then $graph_data2 etc.
foreach ($graph_data$i as $data) :
$variable .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
}
// and so on
endforeach;
The outcome of this script is, as you requested, something of this shape:
{year: month, title: value title: value
We can tweak it a little like this:
foreach ($graph_month as $month):
$variable .= ' { year: "'.$month['month'].'",';
for ($i = 1; $i <=5; $i++) {
//$graph_data$i becomes $graph_data1, then $graph_data2 etc.
foreach ($graph_data$i as $data) :
$variable .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
if ($i != 5) {
$variable .= ", ";
}
endforeach;
}
$variable .=
// and so on
endforeach;
and it becomes:
{ year: month, 'title': 'value', 'title': 'value', ... }
You can put same variable:
foreach ($graph_month as $month) {
$variable .= ' { year: "'.$month['month'].'",';
}
foreach ($graph_data1 as $data) {
$variable .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
}
foreach ($graph_data2 as $data) {
$variable .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
}
// and so on
they will concatenate on every loop.
You can use the for loop like this...
<?php
for($i=0;$i<count($graph_month);$i++)
{
$all_values1 = $graph_data1[$i]['title'] . $graph_data1[$i]['totalValue'];
$all_values2 = $graph_data2[$i]['title'] . $graph_data2[$i]['totalValue'];
$all_values3 = $graph_data3[$i]['title'] . $graph_data3[$i]['totalValue'];
$all_values4 = $graph_data4[$i]['title'] . $graph_data4[$i]['totalValue'];
$all_values5 = $graph_data5[$i]['title'] . $graph_data5[$i]['totalValue'];
}
?>
No need to run too may for loop. It will take some extra time to execute...
Try like this....
Use Empty String
$string = '';
Then use this variable with every for loop
foreach($array1 as $value){
$string.= $value['some_data'];
}
foreach($array2 as $value){
$string.= $value['some_data'];
}
Use this $string as final result
Let PHP worry about the JSON formatting just build the object correctly.
<?php
$tojson = array(
0 => array(),
1 => array(),
2 => array(),
3 => array(),
4 => array(),
5 => array()
);
foreach($graph_month as $month)
$tojson[0]['year'] = $month['month'];
foreach($graph_data1 as $data)
$tojson[1][$data['title']] = $data['totalValue'];
foreach($graph_data2 as $data)
$tojson[2][$data['title']] = $data['totalValue'];
foreach($graph_data3 as $data)
$tojson[3][$data['title']] = $data['totalValue'];
foreach($graph_data4 as $data)
$tojson[4][$data['title']] = $data['totalValue'];
foreach($graph_data5 as $data)
$tojson[5][$data['title']] = $data['totalValue'];
$json = json_encode($tojson);
?>
Related
I am trying to remove the last comma(,) from foreach loop in php with the following code
<?php
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
?>
<?php echo $tag_name; ?> ,
<?php }
?>
Right I am getting result like
Hello, How, sam,
But i wants to remove the last comma
By placing the HTML in a simple string variable and then using rtrim() on the resulting string before outputting it this should remove the final , from the string
<?php
$out = '';
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
// move inside loop and amend to place in a simple string var
$out .= '' . $tag_name . ',';
?>
echo rtrim($out, ',');
You can also use the following code -
<?php
$numItems = count($snippet_tags);
$i = 0;
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
?>
if(++$i === $numItems)
echo "<a href='base_url() ?>tags/<?php echo $tag_name;'> $tag_name</a>";
else echo "<a href='base_url() ?>tags/<?php echo $tag_name;'> $tag_name</a> ,";
<?php
}
?>
Im trying to echo a set of values for categories. What I'd like to do is if there are more than one value, append a comma afterwards. Here's a snippet of what I have:
<?php foreach((get_the_category()) as $category) { echo $category->cat_name . ', '; } ?>
The problem with this is that categories with one value will have a comma at the end.
Alternative 1
Add all values to an array and then just use implode() to glue them all together:
$catArray = [];
foreach((get_the_category()) as $category) {
$catArray[] = $category->cat_name;
}
// Now we can implode the array, using , as the glue
echo implode(', ', $catArray);
Alternative 2
You could also prepend the commas in your loop so you don't need any if-statements:
$glue = '';
foreach((get_the_category()) as $category) {
echo $glue . $category->cat_name;
$glue = ', ';
}
or a shorter version (not as readable though and requires PHP 7+):
foreach((get_the_category()) as $category) {
echo ($glue ?? '') . $category->cat_name;
$glue = ', ';
}
The first iteration won't get any comma in front of it, but the rest will.
You could get the count of results from get_the_category(), set a counter and increment that each time through the loop. Check if $i is equal to the count and if it is, don't add the comma.
Assuming that function is countable and you don't need checks to make sure their aren't 0 results:
<?php
$count = count(get_the_categories());
$i = 1;
foreach((get_the_category()) as $category) {
if($i < $count) {
echo $category->cat_name . ', ';
} else {
echo $category->cat_name;
}
$i++;
}
?>
I have very little experience with PHP, but I'm taking a class that has PHP review exercises. One of them is to create a function that uses a loop to return all values of an array except the first value in an unordered list. I'm assuming there's a way to do this using a foreach loop but cannot figure out how. This is what I had but I feel like I am far off:
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
$favColor = $array['favColor'];
$favMovie = $array['favMovie'];
$favBook = $array['favBook'];
$favWeb = $array['favWeb'];
echo '<h1>' . $myName . '</h1>';
function my_function() {
foreach($array == $myName){
echo '<ul>'
. '<li>' . $favColor . '</li>'
. '<li>' . $favMovie . '</li>'
. '<li>' . $favBook . '</li>'
. '<li>' . $favWeb . '</li>'
. '</ul>';
}
}
my_function();
?>
The correct syntax of foreach is
foreach (array_expression as $key => $value)
instead of
foreach($array == $myName){
function that uses a loop to return all values of an array except the
first value
I'm not sure, what exactly you mean by except the first value. If you are trying to remove first element from the array. Then you could have used array_shift
If you are supposed to use loop then
$count = 0;
foreach ($array as $key => $value)
{
if ($count!=0)
{
// your code
}
$count++;
}
Change the code to following
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
echo '<h1>' . $myName . '</h1>';
function my_function($array)
{
$count = 0;
echo "<ul>";
foreach($array as $key => $value)
{
if($key != "myName")
{
echo "<li>".$value."</li>";
}
}
echo "</ul>";
}
my_function($array);
I have a set of numbers in a table field in database, the numbers are separated by comma ','.
I am trying to do the following:
Step 1. : SELECT set of numbers from database and explode it to array :
$array = explode(',', $set_of_numbers);
Step 2. : Print each element of the array as list item by using foreach loop :
foreach ($array as $list_item => $set_of_numbers){
echo "<li>";
print_r(array_list_items($set_of_numbers));
echo "</li>";}
Please anybody tell me what is wrong. Thank you.
$numbers = '1,2,3';
$array = explode(',', $numbers);
foreach ($array as $item) {
echo "<li>$item</li>";
}
Assuming your original $set_of_numbers is simply a CSV string, something like 1,2,3,4,..., then your foreach is "mostly" ok. But your variable naming is quite bonkers, and your print-r() call uncesary:
$array = explode(',', $set_of_numbers);
foreach($array as $key => $value) {
echo "<li>$key: $value</li>";
}
Assuming that 1,2,3,4... string, you'd get
<li>0: 1</li>
<li>1: 2</li>
<li>2: 3</li>
etc...
$numbers = "1,2,3";
$array = explode(",", $numbers);
/* count length of array */
$arrlength = count($array);
/* using for while */
$x = 0;
while ($x < $arrlength) {
echo "<li>$array[$x]</li>" . PHP_EOL;
$x++;
}
echo PHP_EOL;
/* using for classic */
for ($x = 0; $x < $arrlength; $x++) {
echo "<li>$array[$x]</li>" . PHP_EOL;
}
echo PHP_EOL;
/* using for each assoc */
foreach ($array as $value) {
echo "<li>$value</li>" . PHP_EOL;
}
echo PHP_EOL;
/* using for each assoc key */
foreach ($array as $key => $value) {
echo "<li>$key => $value</li>" . PHP_EOL;
}
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/ZqT4Yi" ></iframe>
You actually don't need to explode on the commas. You can just replace each comma with an ending tag followed by an opening tag and then wrap your whole string in an opening and closing tag.
$set_of_numbers = '1,2,3';
echo '<li>' . str_replace(',', '</li><li>', $set_of_numbers) . '</li>';
// outputs: <li>1</li><li>2</li><li>3</li>
No looping is necessary.
Here is answer for your question to get ride of your problem
$Num = '1,2,3,4,5,';
$Array = explode(',',$Num);
foreach ($Array as $Items)
{
echo "<li>&Items</li>"; // This line put put put in the list.
}
This can easily be achieved by the following code snippet:
<?php
$my_numbers = '1,12,3.2,853.3,4545,221';
echo '<ul>';
foreach(explode(',', $my_numbers) AS $my_number){
echo '<li>'.$my_number.'</li>';
}
echo '</ul>';
The above code will output the following HTML:
<ul><li>1</li><li>12</li><li>3.2</li><li>853.3</li><li>4545</li><li>221</li></ul>
Credits: http://dwellupper.io/post/49/understanding-php-explode-function-with-examples
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Removing last comma in PHP?
So I have the following code:
<?php
foreach ($movie->Genres as $genre):
?>
<?=$genre->name?>,
<?php
endforeach;
?>
And this will give me the following: Action, Drama, Crime, but I don't need this last comma separator - so my question is what would be the best way to avoid that comma ?
Ps.
If that matters I have 4 loops like this one on my page - for actors, directors, etc.
Write you A-tags to an array and join the items.
<?php
$items = array();
foreach ($movie->Genres as $genre):
$items[] = '' . $genre->name . '';
endforeach;
echo join(', ', $items);
?>
$temp = array();
foreach($movie->Genres as $genre) {
$temp[] = <<<EOL
{$genre->name}
EOL;
}
echo implode(',', $temp);
The other option is to use string concatenation, then a substring to delete the trailing comma:
$temp = '';
foreach(...) {
$temp .= ...
}
echo rtrim($temp, ',');
$a = array();
foreach ( $movie->Genres as $v ){
$a[] = '' . $v->name . '';
}
$s = implode(',', $a);
var_dump($s);