[英]How to sort an array by values in another array in PHP
I have an array of image URLs saved from a form submission. 我有一个从表单提交保存的图像URL数组。 I then give users the ability to edit the form values and sort their images using .sortable from jQueryUI. 然后,我使用户能够使用jQueryUI的.sortable编辑表单值并对图像进行排序。 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. 我将排序后的ID添加到一个隐藏的输入中,该输入将它们添加到主POST数据以及表单值的保存数组中。
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. 我需要做的是能够通过$ imageorder var获得以下命令。
<?php foreach($filesArray as $image) { ?>
<img src="<?php /*echo the correct image url*/ ?>">
<?php } ?>
You can achieve that by modifying the foreach
loop as: 您可以通过将foreach
循环修改为:
<?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 所以基本上在订单数组上循环但从原始数组回显
Not sure if I'm understanding 100%, but you could try something like: 不知道我是否能100%理解,但是您可以尝试执行以下操作:
// 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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.