Alex Knopp
Alex Knopp

Reputation: 935

How to sort an array by values in another array in PHP

I have an array of image URLs saved from a form submission. I then give users the ability to edit the form values and sort their images using .sortable from jQueryUI. I take the sorted ID's and add them to a hidden input which adds them to the main POST data and into the saved array of form values.

Saved Form Data:

$dataArray(
   [firstName] => Alex
   [lastName] => Ander The Great
   [imageorder] => image1,image3,image2,image4
)

$filesArray(
   [image1] => url.png
   [image2] => url2.png
   [image3] => url3.png
   [image4] => url4.png
)

$imageorder = explode(',', $dataArray['imageorder']);
/* Gives the following */
array(
   [0] => image1
   [1] => image3
   [2] => image2
   [3] => image4
)

What I need to do is to be able to get the following to order by the $imageorder var.

<?php foreach($filesArray as $image) { ?>
  <img src="<?php /*echo the correct image url*/ ?>">
<?php } ?>

Upvotes: 1

Views: 53

Answers (2)

dWinder
dWinder

Reputation: 11642

You can achieve that by modifying the foreach loop as:

<?php foreach($imageorder as $image) { ?>
  <img src="<?php echo $filesArray[$image] ?>">
<?php } ?>

So basically loop on the order array but echo from the original array

Upvotes: 3

Brett Gregson
Brett Gregson

Reputation: 5913

Not sure if I'm understanding 100%, but you could try something like:

// This would be your POST array, where the values are the image names
$order = [
    "image1",
    "image3",
    "image2",
    "image4",
];

// Your array of images where the keys match the POST array values
$images = [
    "image1" => "url.png",
    "image2" => "url2.png",
    "image3" => "url3.png",
    "image4" => "url4.png",
];

// Empty array to hold the final order
$filesarray = [];

// Iterate the $order array
foreach($order as $item):
    $filesarray[] = $images[$item]; // Push the matching $images key into the array
endforeach;

print_r($filesarray);

Which would output:

Array
(
    [0] => url.png
    [1] => url3.png
    [2] => url2.png
    [3] => url4.png
)

Upvotes: 1

Related Questions