How to randomize images from albums [duplicate] - php

This question already has answers here:
Shuffle an array in PHP
(6 answers)
Closed 9 years ago.
I'm trying to make an image gallery. On the index file I want to show the albums with the images, see; http://www.robcnossen.nl/
I want to randomize the images that are inside these albums but I get all sorts of errors like:
warning: rand() expects parameter 1 to be long, string given in.
My code is;
foreach ($albums as $album) {
?><div><h2><?php
echo'',$album['name'], '';?> </h2><?php
echo'<img src="uploads/thumbs/', $album["id"], '/', $album["imagename"],'" title="" />';
?></div><?php
}
The $album["imagename"] are the images inside the albums and I want to randomize this part. I tried for example:
rand($album["imagename"], 0)
but that gives an error.
I also tried shuffle;
foreach ($albums as $album) {
shuffle($album["imagename"]);
?><div><h2><?php
echo'',$album['name'], '';?></h2><?php
echo'<img src="uploads/thumbs/', $album["id"], '/', $album["imagename"],'" title="" />';
?></div><?php
}
But also there I get only errors.
Can anybody help me with this?
var_dump($albums);
gives
array(2) {
[0]=> array(8) {
["id"]=> string(1) "8"
["timestamp"]=> string(10) "1373890251"
["name"]=> string(7) "Holland"
["description"]=> string(19) "Fantastische foto's"
["count"]=> string(1) "2"
["imagename"]=> string(38) "KONICA MINOLTA DIGITAL CAMERA_428.jpeg"
["image"]=> string(2) "63"
["ext"]=> string(0) ""
}
[1]=> array(8) {
["id"]=> string(1) "9"
["timestamp"]=> string(10) "1376914749"
["name"]=> string(6) "Belgie"
["description"]=> string(11) "Mooi Belgie"
["count"]=> string(1) "2"
["imagename"]=> string(12) "PICT0170.JPG"
["image"]=> string(2) "66"
["ext"]=> string(0) ""
}
}
as result.

shuffle should work for you, but not if you put it inside the foreach loop, like your example code. You need to shuffle before you start the loop. Also, shuffle needs to be called with the array itself, not an item of the array:
shuffle($albums);
foreach ($albums as $album) {
...
}

you should shuffle array out side the loop
<?php
shuffle($albums);
foreach ($albums as $album)
{
?><div><h2>
<?php
echo'',$album['name'], '';
?>
</h2>
<?php
echo'<img src="uploads/thumbs/', $album["id"], '/', $album["imagename"],'" title="" />';
?>
</div>
<?php
}

Related

Unable to skip ranking Post when there is no ranking information in CakePHP2

It's hard to explain it with words, but what I want to do is skip the ranking when there is no ranking information in CakePhp2. For example, I have the following data that contains 7 rows of ranking data. 2 out of the 7 row contains the empty body(2nd and the 5th row). So I made a script to skip the ranking post that is empty. However, Since the 2nd and the 5th rows that have been skipped. The data post that is displayed is 1,3,4,6,7. But I want to the display the ranking like 1,2,3,4,5. In other words, I want to show the 3rd ranking as 2nd and 4th as 3rd and so forth. Sorry for my poor explanation. Simply, I want to skip ranking when there is no ranking information and show the ranking number. (PS: I don't want to alter the DB) I will love to hear from you!
array(7) { [0]=> array(1) { ["Post"]=> array(5) { ["id"]=> string(1) "1" ["title"]=> string(6) "title1" ["body"]=> string(5) "body1" ["created"]=> string(19) "2017-04-04 21:25:43" ["modified"]=> NULL } } [1]=> array(1) { ["Post"]=> array(5) { ["id"]=> string(1) "2" ["title"]=> string(0) "" ["body"]=> string(0) "" ["created"]=> string(19) "2017-04-04 21:25:43" ["modified"]=> NULL } } [2]=> array(1) { ["Post"]=> array(5) { ["id"]=> string(1) "3" ["title"]=> string(6) "title3" ["body"]=> string(5) "body3" ["created"]=> string(19) "2017-04-04 21:25:43" ["modified"]=> NULL } } [3]=> array(1) { ["Post"]=> array(5) { ["id"]=> string(1) "4" ["title"]=> string(6) "title4" ["body"]=> string(5) "body4" ["created"]=> string(19) "2017-04-08 15:48:21" ["modified"]=> NULL } } [4]=> array(1) { ["Post"]=> array(5) { ["id"]=> string(1) "5" ["title"]=> string(0) "" ["body"]=> string(0) "" ["created"]=> string(19) "2017-04-08 16:14:08" ["modified"]=> NULL } } [5]=> array(1) { ["Post"]=> array(5) { ["id"]=> string(1) "6" ["title"]=> string(6) "title6" ["body"]=> string(5) "body6" ["created"]=> string(19) "2017-04-08 16:14:08" ["modified"]=> NULL } } [6]=> array(1) { ["Post"]=> array(5) { ["id"]=> string(1) "7" ["title"]=> string(6) "title7" ["body"]=> string(5) "body7" ["created"]=> string(19) "2017-04-08 16:14:08" ["modified"]=> NULL } } }
Trying to make a script to show the Popular ranking. I really love to hear about some great Hints and samples from you!
<h1>Popular Ranking posts</h1>
<?php $k = 1; ?>
<?php for($i = 0; $i <= count($posts); $i++) { ?>
<ul>
<?php if (!empty($posts[$i]['Post']['body'])) { ?>
<h2><?php echo $posts[$i]['Post']['title']; ?></h2>
<li>
<?php
echo $posts[$i]['Post']['body'];
?>
</li>
//Want to show the number 2 in $k even though the 2nd body data is missing(Currently 3rd data).
<h3 class="ranking_number"><?php echo $k; ?></h3>
<?php } else {
continue;
}?>
</ul>
<?php $k++; } ?>
<h1>Popular Ranking posts</h1>
<?php $k = 1; ?>
<?php for($i = 0; $i <= count($posts); $i++) { ?>
<ul>
<?php if (!empty($posts[$i]['Post']['body'])) { ?>
<h2><?php echo $posts[$i]['Post']['title']; ?></h2>
<li>
<?php
echo $posts[$i]['Post']['body'];
?>
</li>
//Want to show the number 2 in $k even though the 2nd body data is missing(Currently 3rd data).
<h3 class="ranking_number"><?php echo $k; ?></h3>
<?php $k++; } ?>
<?php } else {
continue;
}?>
</ul>
What was changed?
I moved $k++; inside of if, just before else
Why?
What was your code doing:
Set $k to 1.
Post 1 isn't empty, so show it (rank 1).
Increase $k by 1.
Go to next post
Post 2 is empty, so don't show it (rank 2).
Increase $k by 1.
Let's stop there. Your $k was increased with every post, even those skipped, so the third position was 3rd instead of 2nd.
What is my code doing:
Set $k to 1.
Post 1 isn't empty, so show it (rank 1).
Increase $k by 1.
Go to next post
Post 2 is empty, so don't show it (rank 2).
Go to next post
Post 3 isn't empty, so show it (still rank 2).
I hope I helped.

foreach loop Undefined index: title

I am trying to output the results of some blog posts using a foreach loop but I keep getting the error "Undefined index: title"
<?php foreach ($post as $post_item):?>
<div class="postDiv">
<h4><?php echo $post_item['title'];?></h4>
<p><?php echo $post_item['summary'];?></p>
</div>
<?php endforeach;?>
here is my array when calling var_dump($post)
array(4) {
["id"]=> array(5) {
[0]=> string(2) "15"
[1]=> string(2) "16"
[2]=> string(2) "17"
[3]=> string(2) "18"
[4]=> string(2) "19" }
["title"]=> array(5) {
[0]=> string(3) "234"
[1]=> string(2) "11"
[2]=> string(1) "2"
[3]=> string(3) "444"
[4]=> string(5) "title" }
["summary"]=> array(5) {
[0]=> string(3) "213"
[1]=> string(2) "11"
[2]=> string(1) "2"
[3]=> string(3) "444"
[4]=> string(7) "summary" }
["content"]=> array(5) {
[0]=> string(3) "234"
[1]=> string(1) "1"
[2]=> string(1) "2"
[3]=> string(3) "444"
[4]=> string(7) "content" } }
I am a noob at php and I am also using codeigniter if that makes a difference here (I dont think it should). If I use the following code I can print out the posts for the title only but this is not what I want as I want to add in more fields later
<?php foreach ($post['title] as $post_item):?>
<div class="postDiv">
<h4><?php echo $post_item;?></h4>
</div>
<?php endforeach;?>
Here is my final code that worked for me
<?php
foreach (array_reverse(array_keys($post["id"]), true) as $key):?>
<div class="postDiv">
<h4><?php echo $post['title'][$key];?></h4>
<p><?php echo $post['summary'][$key];?></p>
<p><?php echo $post['content'][$key];?></p>
<div style="float:right">
<p><?php echo anchor('admin/edit/'.$post['id'][$key],' [edit]');?></p>
<p><?php echo anchor('admin/delete/'.$post['id'][$key],' [delete]');?></p>
</div>
</div>
<?php endforeach;?>
Your array is somehow misaligned for your design.
<?php foreach (array_keys($post["id"]) as $key):?>
<div class="postDiv">
<h4><?php echo $post['title'][$key];?></h4>
<p><?php echo $post['summary'][$key];?></p>
</div>
<?php endforeach;?>
It looks like your post information is split across multiple array keys based on a numeric reference, so you can use that numeric key reference to access the sibling array keys which contain the rest of your data.
foreach($post['id'] as $key => $id) {
$title = $post['title'][$key];
$summary = $post['summary'][$key];
$content = $post['content'][$key];
}
Just for you understanding:
with foreach ($a as $k) you are iterating an array $a, and putting in each iteration, one first level element in $k.
So, in the first iteration,
$post_item will be
array(5) {
[0]=> string(2) "15"
[1]=> string(2) "16"
[2]=> string(2) "17"
[3]=> string(2) "18"
[4]=> string(2) "19" }
in the second, $post_item will be:
array(5) {
[0]=> string(3) "234"
[1]=> string(2) "11"
[2]=> string(1) "2"
[3]=> string(3) "444"
[4]=> string(5) "title" }
and so on.
I dont even think that this secodn level indexes, 0,1,2,3,4,5 has an specific meannig to you, and for sure, if you do that foreach( array_keys($post["id"]) ...) would be the same as just iterating from harcoded 0 to count($post), and if you iterate foreach( $post["id"] as $k) and then use $k as index to the other elements, that wouldnt work alos, since the values of id, are not the keys of any other elements. so you will get many undefined index warnings.
and also im not sure if the values, the right side of every element, are actually any kind of usefull information for you. So, we could find some tricks here to get the result that you want, but what you need to fix is one step before, when you create $post

Display image and description from plugin(redux) which is an array

I have this array which is inside the variable $cablecar_nhp. When I var_dump() the variable it give me this.
array(3) {
["last_tab"]=> string(0) ""
["media"]=> array(5) {
["url"]=> string(65) "http://sample.com/wp_cablecar/wp-content/uploads/2013/07/Koala.jpg"
["id"]=> string(2) "84"
["height"]=> string(3) "768"
["width"]=> string(4) "1024"
["thumbnail"]=> string(72) "http://sample.com/wp_cablecar/wp-content/uploads/2013/07/Koala-120x95.jpg"
}
["REDUX_imported"]=> bool(false)
}
What i want to do is to get and display the image. Can anybody help me ? I am working on Wordpress.
I'm one of the core devs of Redux. You can access your variable in question by expanding on what Valery said:
echo '<imv src="'.$cablecar_nhp['media']['url'].'">';
Or, do what pr1nc3 suggests above. ;)
You can try to do this:
echo '<img src = "'. $cablecar_nhp['url'] .'">';
extract($cablecar_nhp['media']);
<img src="$thumbnail" height="$height" width="$width" >

PHP Retrieving data values from foreach on sub arrays

I'm trying to get the values of a sub array out in a foreach loop.
I looked at this example as it seemed really relevant to my problem, but unfortunately I've not been able to get it to work, and I'm hoping someone here can pick up where I've gone wrong.
PHP foreach not working with sub-array
I have an array called $booked and inside that array I have a sub array $booked['30_booked'].
Within that second array there are multiple values, such as title, name, address etc.
My code currently looks like this:
foreach($booked['30_booking'] as $new_var){
var_dump('</br>', $booked['30_booking']);
var_dump('</br>', $new_var);
var_dump($new_var['title'], $new_var->title, $booked['30_booking']->title); exit();
}
I've output the data as you can see above in var_dump statements to try and get one of these methods to work.
Unfortunately nothing within $new_var is pulling out the title, but $booked['30_booking']->title
Have I not put it into the foreach statement correctly?
All help appreciated - thanks!
EDIT:
Main array output snippet:
array(6) { ["30_booked"]=> object(stdClass)#21 (34) { ["id"]=> string(2) "30" ["title"]=> string(2) "Ms" ["firstname"]=> string(5) "FIRST NAME" ["surname"]=> string(9) "LAST NAME" ["address"]=> string(6) "- -- -" ["postcode"]=> string(7) "FAK E99" ["country"]=> string(14) "United Kingdom" ["phone"]=> string(11) "01221111111" ["alt_phone"]=> string(0) "" ["email"]=> string(25) "fake#fake.co.uk" ["notes"]=> string(8) "FAKE DEAL" } }
EDIT 2:
Sub Array $booked['30_booking'] snippet:
object(stdClass)#21 (34) { ["id"]=> string(2) "30" ["title"]=> string(2) "Ms" ["firstname"]=> string(5) "FIRST NAME" ["surname"]=> string(9) "LAST NAME" ["address"]=> string(6) "- -- -" ["postcode"]=> string(7) "FAK E99" ["country"]=> string(14) "United Kingdom" ["phone"]=> string(11) "01221111111" ["alt_phone"]=> string(0) "" ["email"]=> string(25) "fake#fake.co.uk" ["notes"]=> string(8) "FAKE DEAL" }
EDIT 3:
My var_dump of the $new_var by itself is bringing back the value of the id - but when I try and get the second value out the sub array "title" it doesn't return anything.
FINAL FIX:
Thanks to Kita I realised I was returning a std class object and not a second array, something that I stupidly missed the first time round. Because of that I can't actually foreach on the object.
Which led me to this post which will help me fix the issue:
PHP foreach array with stdClass Object
Thank you very much for all your help!!!
You expected an array inside $booked['30_booking'] but in fact there was a stdClass object.
array(6) {
["30_booked"]=> object(stdClass)#21 (34) {
["id"]=> string(2) "30"
["title"]=> string(2) "Ms"
["firstname"]=> string(5) "FIRST NAME"
["surname"]=> string(9) "LAST NAME"
["address"]=> string(6) "- -- -"
["postcode"]=> string(7) "FAK E99"
["country"]=> string(14) "United Kingdom"
["phone"]=> string(11) "01221111111"
["alt_phone"]=> string(0) ""
["email"]=> string(25) "fake#fake.co.uk"
["notes"]=> string(8) "FAKE DEAL"
}
//I assume you have left out the other array elements from the Main array snippet.
}
Getting stdClass instead of array usually happens when you parse a JSON string with json_decode() without the second parameter.
// without second parameter
var_dump( json_decode( '{"id":"30"}' ) );
object(stdClass)#1 (1) {
["id"]=>
string(2) "30"
}
// 'true' as second parameter
var_dump( json_decode( '{"id":"30"}', true ) );
array(1) {
["id"]=>
string(2) "30"
}
Above examples are hosted at: http://ideone.com/GNMRlD
Since stdClass object itself does not provide iteration functionality, using it with foreach will yield errors.
You can convert stdClass into array with functions such as http://www.if-not-true-then-false.com/2009/php-tip-convert-stdclass-object-to-multidimensional-array-and-convert-multidimensional-array-to-stdclass-object/ .
For eg. if your array looks like below. foreach which I used will be working
$new_array = array(array('total'=>array('title'=>'test','text'=>'text')));
foreach ($new_array as $val)
{
print_r($val['total']['title']); // Use this for array
print_r($val->total->title); // Use this for object
}
if your array looks like below. Use the below foreach.
$new_array = array(array('total'=>array(array('title'=>'test','text'=>'text'),array('title'=>'test1','text'=>'text1'))));
foreach ($new_array as $val)
{
foreach($val['total'] as $new_val)
{
print_r($new_val['title']);
}
}
You can try this, I hope that helps you
foreach($booked as $new_var){
var_dump('</br>', $new_var);
var_dump('</br>',$new_var['30_booking']->title);
}
I think in your foreach there is mistake of word 30_booking
since in your main array out put display it shows 30_booked
check that also

php code - trying to loop array

I am noticing some strange behavior while looping through some data. I'm sure it's something simple, but I can't seem to be able to find the bug.
I have the following logic:
<?php
print 'dumping data : <BR>';
var_dump($portvlan);
print '<BR>';
print 'looping through data: <BR>';
foreach ($portvlan as $vlandetail){
echo 'Vlanid: '.$vlandetail['VlanId'].'<BR>';
echo 'Name: '.$vlandetail['Name'].'<BR>';
echo 'Mode: '.$vlandetail['Mode'].'<BR>';
}
?>
This is the output that I'm getting:
dumping data :
array(3) { ["VlanId"]=> string(2) "33" ["Name"]=> string(6) "USR_33" ["Mode"]=> string(6) "Access" }
looping through data:
Vlanid: 3
Name: 3
Mode: 3
Vlanid: U
Name: U
Mode: U
Vlanid: A
Name: A
Mode: A
What I was expecting was to see it print a row with 3 cells, with the following values:
33, USR_33, Access.
Can you tell me where I'm going wrong?
Thanks.
EDIT 1
This logic works fine when the $portvlan array has more than one entry.
For example, on another set of data, the var_dump gives this result:
array(6) { [0]=> array(3) { ["VlanId"]=> string(1) "1" ["Name"]=> string(1) "1" ["Mode"]=> string(5) "Trunk" } [1]=> array(3) { ["VlanId"]=> int(2) ["Name"]=> int(2) ["Mode"]=> string(5) "Trunk" } [2]=> array(3) { ["VlanId"]=> int(3) ["Name"]=> int(3) ["Mode"]=> string(5) "Trunk" } [3]=> array(3) { ["VlanId"]=> int(4) ["Name"]=> int(4) ["Mode"]=> string(5) "Trunk" } [4]=> array(3) { ["VlanId"]=> int(5) ["Name"]=> int(5) ["Mode"]=> string(5) "Trunk" } [5]=> array(3) { ["VlanId"]=> string(2) "33" ["Name"]=> string(2) "33" ["Mode"]=> string(5) "Trunk" } }
And the loop logic works fine.
$vlandetail will be populated with a different item from the array on every iteration of the loop. You shouldn't be treating $vlandetail as an array. Just use it directly.
To get the key name of the array entry, you have to change the loop structure to this:
foreach ($portvlan as $key => $vlandetail) {
echo $key . ': ' . $vlandetail . '<br>';
}
How you get your $portvlan?
If you can know is $portvlan is not an array of $vlandetail, you can simply do this,
$portvlan = array($portvlan);
// start loop
Or you can do this before you loop it, to make sure $portvlan is a numerical array formed by $vlandetail
$portvlan = (isset($portvlan[0]))?$portvlan:array($portvlan);
// start loop

Categories