• 0

Split directory contents into array.


Question

So far I have this:


<?php
$image_dir = scandir("images");
$images = array_diff($image_dir, array('.', '..'));

var_dump($images);

?>

This loads the specified directory contents into an array which is a good start!

The array_diff function removes the . and .. from the array (linux server).

I'm then left with image1, image1_thumb, image2, image2_thumb, etc. in the array.

I want to split these into separate items, so that the image and the thumb associated with that image will each have it's own section in the array? I hope that makes sense.

Cheers,

Alex

Edit: urgh wrong section, should be in web design and programming.

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

Does an image always have a thumb, and are they always next to each other in the array? If so you can use array_chunk($arr, 2).

$arr = array('image1', 'image1_thumb', 'image2', 'image2_thumb');
$arr = array_chunk($arr, 2);[/CODE]

[code]
array (size=2)
  0 => 
    array (size=2)
      0 => string 'image1' (length=6)
      1 => string 'image1_thumb' (length=12)
  1 => 
    array (size=2)
      0 => string 'image2' (length=6)
      1 => string 'image2_thumb' (length=12)

Link to comment
Share on other sites

  • 0

That has worked brilliantly! Thank you so much :)

I'm newish to arrays so I wonder if you'd be able to help me with the next bit...

Here's how the array looks:


Array
(
	[0] => Array
		(
			[0] => image1.jpg
			[1] => image1_thumb.jpg
		)

	[1] => Array
		(
			[0] => image2.jpg
			[1] => image2_thumb.jpg
		)

	[2] => Array
		(
			[0] => image4.jpg
			[1] => image4_thumb.jpg
		)

//etc......
)

I'm would like to recursively tech the contents like so:

echo 'somehtmlgoeshere' image_name 'morehtml' thumb_name 'lastbitofhtml';

I'm not sure where to start :s

Cheers,

Alex

Link to comment
Share on other sites

  • 0

I know I can do this:

echo $images[0][1];

and it will echo that specific area of the array but I want it to do the following:

echo $images[0][0]; echo $images[0][1];
echo $images[1][0]; echo $images[1][1];
etc....

until reaching the end of the array.

Clues?

Link to comment
Share on other sites

  • 0

So this sorta works:


foreach ($images as $value1) {
	foreach ($value1 as $value2) {
		echo "$value2\n";
	}
}

It doesnt put the values in any order though, just prints the contents of the array one after the other.

I want the image and then the thumb printed on the same lines. Then a new line for the next one. Make sense?

Cheers.

Link to comment
Share on other sites

This topic is now closed to further replies.