Wednesday, 18 September 2013

PHP - Remove items from an array with given parameter

PHP - Remove items from an array with given parameter

I've searched around and I found some similar questions asked, but none
that really help me (as my PHP abilities aren't quite enough to figure it
out). I'm thinking that my question will be simple enough to answer, as
the similar questions I found were solved with one or two lines of code.
So, here goes!
I have a bit of code that searches the contents of a given directory, and
provides the files in an array. This specific directory only has .JPG
image files named like this:
Shot01.jpg Shot01_tn.jpg
so on and so forth. My array gives me the file names in a way where I can
use the results directly in an tag to be displayed on a site I'm building.
However, I'm having a little trouble as I want to limit my array to not
return items if they contain "_tn", so I can use the thumbnail that links
to the full size image. I had thought about just not having thumbnails and
resizing the images to make the PHP easier for me to do, but that feels
like giving up to me. So, does anyone know how I can do this? Here's the
code that I have currently:
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new
RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
foreach($array as $fileObject):
$filelist = str_replace("_tn", "", $fileObject->getPathname());
echo $filelist . "<br>";
endforeach;
I attempted to use a str_replace(), but I now realize that I was
completely wrong. This returns my array like this:
Array
(
[0] => featured/Shot01.jpg
[1] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03.jpg
)
I only have 3 images (with thumbnails) currently, but I will have more, so
I'm also going to want to limit the results from the array to be a random
3 results. But, if that's too much to ask, I can figure that part out on
my own I believe.
So there's no confusion, I want to completely remove the items from the
array if they contain "_tn", so my array would look something like this:
Array
(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
Thanks to anyone who can help!

No comments:

Post a Comment