PHP : Get 9 random value from array - php

I'm struggling to get 9 random values from an array, I have this php code which works fine but returns all the values. I need to only select 9 random ones with an foreach preferably.
<?php
foreach($gallerystreamobjects as $smallgallery) {
$smallgalleryArray = $smallgallery->GalleryPictures;
}
$arr = explode(",", $smallgalleryArray);
foreach($arr as $value)
{
?>
<a href="cms/uploads/<?php echo $value;?>" class="swipebox">
<div class="gallery-item-small" >
<div style="background-image:url('cms/uploads/<?php echo $value;?>')"></div>
</div>
</a>
<?php
}
?>

The function array_rand() will solve your problem:
$randomKeys = array_rand($arr, 9);
foreach($randomKeys AS $key){
$value = $arr[$key];
//do whatever you like
}

I managed to use an quick and easy way to do this. Not that its the right way, but ja, so I tried array_rand() but I kept on getting errors on it in its most basic way, I found out it was to do with the values actually going missing. Here is my current solution :
<?php
$smallgalleryArray = $gallerystreamobjects[0]->GalleryPictures;
$arr = explode(",", $smallgalleryArray);
shuffle($arr);
$count=0;
foreach($arr as $value) {
$count++;
if($count<10){
?>
<a href="cms/uploads/<?php echo $value;?>" class="swipebox">
<div class="gallery-item-small" >
<div style="background-image:url('cms/uploads/<?php echo $value;?>')"></div>
</div>
</a>
<?php
}
}
?>

Related

Style array_slice output

I have the following PHP script that extracts the last 5 rows from file X.
<?php
$f=file("x.txt");
$last=array_slice($f, -5);
echo implode("<br>",$last);
?>
The output is the following:
John
Christmas
George
Luck
Sun
Question: How can I make the output to be clickable links? Example of output I want:
John
Christmas
George
Luck
Sun
I tried something like:
echo implode("<br> <a href='http://google.com/q?' . $last . ''>");
But it didn't work at all... any solutions? Thanks!
Instead of implode(), you can just loop thru $last then echo desired html line
foreach ($last as $value) {
echo "<a href='http://www.google.com?q=$value'>$value</a><br>";
}
Try this :-
<?php
$names = array('John','Christmas','George','Luck','Sun');
foreach($names as $name) {
echo "<br>$name";
}
?>
Happy Coding :-)
I think no need to use implode function.
I have modified your code as below. Hope this will help.
<?php
$f=file("x.txt");
$last=array_slice($f, -5);
if(!empty($last)){
foreach ($last as $value) {
?>
<a href='http://www.google.com?q=<?php echo $value;?>'><?php echo $value;?></a><br>
<?php
}
}
?>
<?php
$f = array("Volvo", "BMW", "Toyota"); //$f=file("x.txt");
$last=array_slice($f, -5);
echo implode("<br>",$last);
foreach ($last as $value) {
echo "<a href='http://www.google.com?q=$value'>$value</a> , ";
}
?>
You can use array_map and implode if you don't want to loop.
$last = array('John','Christmas','George','Luck','Sun');
function addlink($last)
{
return('' . $last .'');
}
$last = array_map("addlink",$last);
echo implode("\n", $last);
https://3v4l.org/l3nME

Loop with curly brackets causes wrong output

I created 2 simple examples:
First example:
<?php $arr = array(1,2,3,4,5); ?>
<?php foreach ($arr as $element) ?>
<?php { ?>
<?php echo $element; ?>
<?php } ?>
output:
5 //Is this result wrong?
Second example:
<?php $arr = array(1,2,3,4,5); ?>
<?php foreach ($arr as $element) { ?>
<?php echo $element; ?>
<?php } ?>
output:
12345
What did I miss about the PHP syntax?
I know that there is an alternative foreach syntax, but in my opinion both shown examples should result in the same output. (Code tested with PHP version: 5.6.12)
Edit:
I know the tags are not needed in every line.
To be more precise: I want to know why the two examples give me 2 different results?
Based on the output, my guess is that:
<?php $arr = array(1,2,3,4,5); ?>
<?php foreach ($arr as $element) ?>
<?php { ?>
<?php echo $element; ?>
<?php } ?>
is being interpreted as:
<?php
$arr = array(1,2,3,4,5);
foreach ($arr as $element);
{
echo $element;
}
?>
Looks like a bug in the interpreter? See comments by Rizier123:
Not a bug: stackoverflow.com/q/29284075/3933332
The brackets after the foreach()/Do nothing here/; is just a statement-group: php.net/manual/en/control-structures.intro.php
Anyways, the code looks atrocious with the way you have written it. Please opt for cleaner code.
Reading through the comments under the question I think Jon Stirling explain this symptom the best:
Just guessing, but perhaps the ?> in the first example is actually being taken as the statement end (loops can be used without braces). At that point, the loop has happened and $element is the last value. Then the braces are just take as a code block which you echo, which is 5.
Over using <? php> is your problem.
You are completing the foreach context before outputting the result and not doing that in the second.
Look at your examples carefully and you should see what you are doing differently.
I don't know why you use so many php tags, but that's why it doesn't work!
try this:
<?php $arr = array(1,2,3,4,5);
foreach ($arr as $element)
{
echo $element;
} ?>
You don't need to use <?php and ?> every single line simply do:
<?php
$arr = array(1,2,3,4,5);
foreach ($arr as $element) {
echo $element;
}
?>
Or alternative syntax:
<?php
$arr = array(1,2,3,4,5);
foreach ($arr as $element)
{
echo $element;
}
?>
Or
<?php
$arr = array(1,2,3,4,5);
foreach ($arr as $element):
echo $element;
endforeach;
?>
When you are doing this:
<?php foreach ($arr as $element) ?>
<?php { ?>
<?php echo $element; ?>
<?php } ?>
PHP loops nothing because it sees
foreach ($arr as $element)
{
}
echo $element;

Output All Currency Values using 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>

Grab first item of array through custom content types manager

I'm using Wordpress and Custom Content Types Manager, how do I go about editing the code below to only grab the first image from the array below?
<?php
$array_of_images = get_custom_field('slide_images:to_array');
foreach ($array_of_images as $img_id) {
?>
<div><?php print CCTM::filter($img_id, 'to_image_tag'); ?> </div>
<?php } ?>
I tried adding in array_slice($array_of_images, 0, 1); but no luck so far. Thanks!
If all else fails you could do the same as what you have except add an $i value. It's kind of dumb but it would work if you can't get a normal method to work. This would be a last ditch effort sort of thing...
<?php
$array_of_images = get_custom_field('slide_images:to_array');
$i = 0;
foreach ($array_of_images as $img_id) { ?>
<div><?php print CCTM::filter($img_id, 'to_image_tag'); ?> </div>
<?php if($i == 0) break; } ?>
$key = array_keys($array_of_images);
$value = $array_of_images[$key[0]];

PHP array output to a javascript function

I am trying to connect a database with php and display result dynamically using javascript.
Here's What i am trying to do -
<?php
function mainMenu($q){
$res=array();;
$q->setFetchMode(PDO::FETCH_NUM);
while($r = $q->fetch()){
array_push($res, "
<li>
<a class='gn-icon ".mysql_real_escape_string($r[0])."'>".mysql_real_escape_string($r[1])."
</a>
</li>");
}
return $res;
} ?>
Now here is the html , which definitely works
<ul id="sidemenu" class="gn-menu">
<?php
$a=mainMenu($q);
foreach ($a as $value) {
echo $value;
}
?>
</ul>
but when i try this -
<script>
$('#sidemenu').html(<?php
$b=mainMenu($q);
foreach ($b as $value) {
echo "$value";
}
?>);
</script>
It doesnt work the, i just see blank space in my source and nothing is printed in the list, can anyone tell me where i am going wrong...
<?php
function mainMenu($q) {
$res=array();
$q->setFetchMode(PDO::FETCH_NUM);
while( $r = $q->fetch() ) {
array_push($res, "<li><a class='gn-icon ".mysql_real_escape_string($r[0])."'>".mysql_real_escape_string($r[1])."</a></li>");
}
return $res;
}
?>
<script>
$('#sidemenu').html("<?=implode('',mainMenu($q))?>");
</script>
you need to escape the single quote in your output using "Backslash",
<a class=\'gn-icon ".mysql_real_escape_string($r[0])."\'>".mysql_real_escape_string($r[1])." </a>
and you need use the .html like this,
.html('<?php $b=mainMenu($q); foreach ($b as $value) { echo $value;} ?>')

Categories