Barry Jarvis Barry Jarvis - 2 years ago 292
PHP Question

Change order of array

I have some code in Wordpress that gets the images that are attached to a specific post.

It puts all the information of that post in to an array then pulls the images from it using the built in Wordpress function


I then use a
loop to display the images in an image slider.
The problem I have is that it is putting 'image1' in position 1 of the array, and 'image2' in position 0 of the array.

So it's displaying image 2 first.

here's my code.

$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID

$attachments = get_posts( $args );
$images = array($attachments);
echo '<div id="postSlider"><div class="slides_container">';
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<div>' . wp_get_attachment_image($attachment->ID, 'large') . '</div>';

echo '</div>';
if(sizeof($attachments) > 1) {
echo '<div class="sliderControls">
<a href="#" class="sliderBtnPrev">Previous</a>
<a href="#" class="sliderBtnNext">Next</a>
<span class="sliderPagination">1 of 3</span>
echo '</div>';

From what I've read the
loop will preserve the order of the array. So, I'm thinking I need to change the order of the array so that the loop sees 'image1' (array position [1]) first.

My knowledge of arrays is limited and so I'm not sure how to do this.. any help appreciated.

Answer Source

If you want to change the order programmatically, have a look at the various array sorting functions in PHP, especially

  • uasort()— Sort an array with a user-defined comparison function and maintain index association
  • uksort()— Sort an array by keys using a user-defined comparison function
  • usort()— Sort an array by values using a user-defined comparison function

but for wordpress checkout this

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download