1

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 } ?>
3
  • 1
    Could you try explaining the problem again? Commented Sep 9, 2019 at 15:36
  • @glend Im trying to order the values in filesArray by imageorder. Commented Sep 9, 2019 at 15:41
  • Sort of duplicate of stackoverflow.com/questions/348410/…, but think dWinder's answer is probably more suited for what you want. Commented Sep 9, 2019 at 15:48

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.