Use variable in php array - arrays

I have this code:
<?php
$query = mysqli_query($sqlnews,'SELECT * FROM news ORDER BY id DESC');
$count = 0;
while($count < 4 && $output = mysqli_fetch_assoc($query))
{
$count++;
echo '<div class="item"><div class="testimonials-box"><div class="testimonial-details"><h1><a class="news_subject" href="news.php?newsid='.$output['id'].'">'.$output['subject_en'].'</a></h1><br />';
echo '<span class="news_author">'.$output['postedby'].'</span><b> | </b>';
echo '<span class="news_date">'.date('l, d F Y', strtotime($output['date'])).'</span><div class="devider"></div>';
echo '<span class="news_short">'.$output['short_description_en'].'</span></div></div>';
echo '</div>';
}
?>
I wanna get the variable $output using array from another variable that also has an array, like this: $output['$id["1"]']
I get an error when trying to do this that says: Undefined index: $id["1"] in.
Notice that the array from $id is from antoher php file that is included in this one.
Thanks!

Just remove the apostrophes around $id["1"]:
$output[$id["1"]]
Otherwise, the '$id["1"]' is treated literally as a string index.

Related

How is it possible to echo a multidimension array value witout loop in php

I have a multidimension array, in fact a 2 dimension array, I like to echo all the value of the second index... something like that : $cars[0][0]
$cars = array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);
$cars[0][0] will get me : Volvo. what i need is : Volvo 100 96. Is there is a way to echo this ?.. not print_r or var_dump. does a php function exist to do that ?
let's say now the RESULT array is $cars... 3 sub array value... i what them out. based on answer i try that :
foreach ($cars as $singleArray => $key) {
$result = "";
$result = implode(' ', $singleArray[$key]);
echo '# '. $key .' '. $result .'<br/>';
}
there is an ERROR : Warning: implode() [function.implode]: Invalid arguments passed in /home/studiot/public_html/previsite.com/data/array2.php on line 46
Array
i have done it like this :
foreach ($cars as $singleArray) {
$keyValue ++;
$result = "";
$result .= implode(' ', $singleArray);
echo '(# '. $keyValue .') -> '. $result .'<br/>';
}
You can simply implode the array you want to output with spaces:
echo implode(' ', $cars[0]);
// Volvo 100 96
Docs: http://nz1.php.net/function.implode
EDIT
I see you've tried to use a foreach loop, your syntax is wrong for it. foreach parameters are input array as array key => array value. So you'll implode the value (which is another array. Like this:
foreach ($cars as $key => $value) {
$result = implode(' ', $value);
echo '# '. $key .' '. $result .'<br/>';
}

how to print out all certian json data in database?

What I'm trying is I have a page which you can input 3 angel integers and submit.
After you submit the data will be saved in database using json encode
{"angle1":"60","angle2":"60","angle3":"90","submit":"Submit"}
The above is what's saved into a row
I used
<?php
$sql = "SELECT * FROM wp_options WHERE option_name LIKE 'angle%' ORDER BY option_name";
$options = $wpdb->get_results($sql);
foreach ( $options as $option )
{
echo '<p><b>'.$option->option_name.'</b> = '
.esc_attr($option->option_value).'</p>'.PHP_EOL;
$line = json_decode($option->option_value, true);
}
echo '<span style="color:#f00;">'.'Angel 1 : '.$line['angle1'].'</span><br>';
echo '<span style="color:#0f0;">'.'Angel 2 : '.$line['angle2'].'</span><br>';
echo '<span style="color:#00f;">'.'Angel 3 : '.$line['angle3'].'</span><br>';
This prints out angel 1 : ## where ## is the angle entered and so on.
I also made a simple 2d piechart which shows the angles.
the problem I'm having is if I submit another 3 angles then my result only shows the MOST RECENT angles entered even if there are two or more in the database.
For example in my database I can see
{"angle1":"60","angle2":"60","angle3":"90","submit":"Submit"}
{"angle1":"60","angle2":"60","angle3":"180","submit":"Submit"}
{"angle1":"30","angle2":"60","angle3":"180","submit":"Submit"}
but the result only prints 30 60 and 180 instead of printing all three.
Anyone mind giving me a hand on how I can print all three data out or at least all three sets of the angles. I believe once I figured that out I can then print out all the piecharts with all the angles instead right now only the most recent angle and the piechart are printed.
Thanks a lot people~
P.S.
I'm so so so stupid I didn't put those echo into the foreach loop but my other question is I believe I need to input my codes below into the foreach loop but there are so many tags is there a way to input all those into the foreach loop instead of doing something like echo canvas id="piechart1" blah blah blah and do it bit by bit?
<canvas id="piechart1" width="100" height="100"></canvas>
<script src="<?php echo get_stylesheet_directory_uri().'/piechart.js'; ?>"></script>
<script>
var chartId = "piechart1";
var colours = ["#f00", "#0f0", "#00f"];
var angles = [<?php echo $line['comp2052_angle1'].','.
$line['comp2052_angle2'].','.
$line['comp2052_angle3'];
?>];
piechart(chartId, colours, angles);
</script>
It not print 3 results, because you put them out of for scope. It only print the last $line because $line will replace every for loops.
To fixed it.
<?php
$sql = "SELECT * FROM wp_options WHERE option_name LIKE 'angle%' ORDER BY option_name";
$options = $wpdb->get_results($sql);
foreach ( $options as $option )
{
echo '<p><b>'.$option->option_name.'</b> = '
.esc_attr($option->option_value).'</p>'.PHP_EOL;
$line = json_decode($option->option_value, true);
// put the echo in for scope
echo '<span style="color:#f00;">'.'Angel 1 : '.$line['angle1'].'</span><br>';
echo '<span style="color:#0f0;">'.'Angel 2 : '.$line['angle2'].'</span><br>';
echo '<span style="color:#00f;">'.'Angel 3 : '.$line['angle3'].'</span><br>';
echo '<hr/>'; // to separate each data
}
You can stored line into array then print their when you want it. for example.
<?php
$sql = "SELECT * FROM wp_options WHERE option_name LIKE 'angle%' ORDER BY option_name";
$options = $wpdb->get_results($sql);
// added to stored line
$line = array();
foreach ( $options as $option )
{
echo '<p><b>'.$option->option_name.'</b> = '
.esc_attr($option->option_value).'</p>'.PHP_EOL;
$line[] = json_decode($option->option_value, true);
}
Then. You can mixed html and php in the pretty ways like code below.
<?php foreach($line as $i => $l): ?>
<canvas id="piechart<?php echo $i?>" width="100" height="100"></canvas>
<script>
var chartId = "piechart<?php echo $i?>";
var colours = ["#f00", "#0f0", "#00f"];
var angles = [<?php echo $l['angle1'].','.
$l['angle2'].','.
$l['angle3'];
?>];
piechart(chartId, colours, angles);
</script>
<?php endforeach; ?>
Put this anywhere in html before the code above
<script src="<?php echo get_stylesheet_directory_uri().'/piechart.js'; ?>"></script>

Horizontal calendar using PHP

You can see what I am trying to make here http://perthurbanist.com/website/calendarloader.php. Basically it is a horizontal calendar and you will use arrows to move. What I want to do is have the code display all the months horizontally along with all the days (starting from the current month and day). I know how to get the current day using the date function but I don't know how to make the calendar start at that date. I also want it to load lots of months (maybe 2-3 years worth). How do I do those two things.
<?php
$showday = date("j");
$displaymonth = date("M");
$showmonth = date("n");
$showyear = date("Y");
$day_count = cal_days_in_month(CAL_GREGORIAN, $showmonth, $showyear);
echo '<ul class="calendarnavigation">';
echo '<li class="month">' . $displaymonth . '</li>';
for($i=1; $i<= $day_count; $i++) {
echo '<li>' . $i . '</li>';
}
echo '</div>';
?>
If you know (or are able to calculate how far ahead you want to go in days you could try this:
for($i=0; $i<$numberOfDays; $i++)
{
$timestamp=mktime(0,0,0,date("m"),date("d")+$i,date("Y"));
$day=date("d", $timestamp);
$month=date("m", $timestamp);
$year=date("Y", $timestamp);
...Your display stuff here...
}
On each iteration of the loop the $timestamp will advance one day and using it in your date functions will give you the information about the date that you need to create your display.
Maybe in your case you can use
echo '<ul class="calendarnavigation">';
for($i=0; $i<$numberOfDays; $i++)
{
$timestamp=mktime(0,0,0,date("m"),date("d")+$i,date("Y"));
$showday=date("j", $timestamp);
$displaymonth=date("M", $timestamp);
$showmonth=date("n", $timestamp);
$showyear=date("Y", $timestamp);
if($showday=="1")
{
echo '<li>'.$displaymonth.'</li>';
}
echo '<li>'.$showday.'</li>';
}
echo '</ul>';

PHP array only prints first letter of each item

The code below is only printing the first letter of each array item. It's got me quite baffled.
require_once 'includes/global.inc.php';
print_r($site->bookmarkTags(1));
$index = 0;
foreach ($site->bookmarkTags(1) as $tag) {
echo $tag['$index'];
$index = $index + 1;
}
print_r return:
Array ( [0] => Wallpapers [1] => Free )
the loop:
WF
Try echo $tag, not $tag['$index']
Since you are using foreach, the value is already taken from the array, and when you post $tag['$index'] it will print the character from the '$index' position :)
It seems you've attempted to do what foreach is already doing...
The problem is that you're actually echoing the $index letter of a non-array because foreach is already doing what you seem to be expecting your $index = $index+1 to do:
require_once 'includes/global.inc.php';
print_r($site->bookmarkTags(1));
$index = 0;
foreach ($site->bookmarkTags(1) as $tag) {
echo $tag; // REMOVE [$index] from $tag, because $tag isn't an array
$index = $index + 1; // You can remove this line, because it serves no purpose
}
require_once 'includes/global.inc.php';
// Store the value temporarily instead of
// making a function call each time
$tags = $site->bookmarkTags(1);
foreach ($tags as $tag) {
echo $tag;
}
This should work. The issue might be because you're making a function call every iteration, versus storing the value temporarily and looping over it.

PHP> echo string separated by lines of 3 words each?

I need make something that includes a function that uses explode to create an array. I have seen several examples, but near the end I really get confused! Is there a simple readable way for this? (//comments?)
Take for instance a piece of text:
"This is a simple text I just created".
The output should look like this:
This is a
simple text I
just created
So the explode should split the text into lines of 3 words each.
$text = "This is a simple text I just created";
$text_array = explode(" ", $text);
$chunks = array_chunk($text_array, 3);
foreach ($chunks as $chunk) {
$line = $impode(" ", $chunk);
echo $line;
echo "<br>";
}
Try this is what you need:
<?php
$text = "This is a simple text I just created";
$text_array = explode(' ', $text);
$i = 1; // I made change here :)
foreach($text_array as $key => $text){
if(ceil(($key + 1) / 3) != $i) { echo "<br/>"; $i = ceil(($key + 1) / 3); }
echo $text.' ';
}
?>
Result:
This is a
simple text I
just created
Use substr() function link
Example:
<?php
$rest = substr("abcdef", -1); // returns "f"
$rest = substr("abcdef", -2); // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>
In your case:
<?php
$rest = substr("This is a simple text I just created", 0, 15); //This will return first 15 characters from your string/text
echo $rest; // This is a simpl
?>
explode just splits the string at a specified character. There's nothing more to it.
explode(',', 'Text,goes,here');
This splits the string whenever it meets a , and returns an array.
to split by a space character
explode(' ', 'Text goes here');
This splits only by a space character, not all whitespace. Preg_split would be easier to split by any whitespace
So something like...
function doLines($string, $nl){
// Break into 'words'
$bits = explode(' ', $string);
$output = '';
$counter=0;
// Go word by word...
foreach($bits as $bit){
//Add the word to the output...
$output .= $bit.' ';
//If it's 3 words...
if($counter==2){
// Remove the trailing space
$output = substr($output, 0, strlen($output)-1);
//Add the separator character...
$output .=$nl;
//Reset Counter
$counter=0;
}
}
//Remove final trailing space
$output = substr($output, 0, strlen($output)-1);
return $output;
}
Then all you have to is:
echo doLines("This is a simple text I just created", "\n");
or
echo doLines("This is a simple text I just created", "<br />");
..depending if you just want new lines or if you want HTML output.

Resources