如何在PHP中按另一个数组中的值对数组进行排序
我有一个从表单提交保存的图像URL数组。然后,我允许用户使用jQueryUI中的.sortable编辑表单值并对其图像进行排序。我获取已排序的ID并将其添加到隐藏输入中,该输入将它们添加到主POST数据和保存的表单值数组中 保存的表单数据:如何在PHP中按另一个数组中的值对数组进行排序,php,arrays,sorting,Php,Arrays,Sorting,我有一个从表单提交保存的图像URL数组。然后,我允许用户使用jQueryUI中的.sortable编辑表单值并对其图像进行排序。我获取已排序的ID并将其添加到隐藏输入中,该输入将它们添加到主POST数据和保存的表单值数组中 保存的表单数据: $dataArray( [firstName] => Alex [lastName] => Ander The Great [imageorder] => image1,image3,image2,image4 ) $f
$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
)
我需要做的是能够通过$imageorder变量订购以下内容
<?php foreach($filesArray as $image) { ?>
<img src="<?php /*echo the correct image url*/ ?>">
<?php } ?>
不确定我是否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);
这将产生:
Array
(
[0] => url.png
[1] => url3.png
[2] => url2.png
[3] => url4.png
)
不确定我是否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);
这将产生:
Array
(
[0] => url.png
[1] => url3.png
[2] => url2.png
[3] => url4.png
)
通过将foreach循环修改为:
<?php foreach($imageorder as $image) { ?>
<img src="<?php echo $filesArray[$image] ?>">
<?php } ?>
因此,基本上是在order数组上循环,但从原始数组回显,您可以通过将foreach循环修改为:
<?php foreach($imageorder as $image) { ?>
<img src="<?php echo $filesArray[$image] ?>">
<?php } ?>
因此,基本上是在order数组上循环,但从原始数组回显您能再次尝试解释这个问题吗?@glend我正在尝试按imageorder对FileArray中的值进行排序。有点重复,但是我认为德温德的答案可能更适合你想要的。你能再解释一下这个问题吗?@glend我试图按imageorder对FileArray中的值排序。有点重复,但我认为德温德的答案可能更适合你想要的。