PHP用另一个数组对多维数组进行排序

编程入门 行业动态 更新时间:2024-10-27 00:22:21
本文介绍了PHP用另一个数组对多维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何基于另一个数组对已定义的数组进行排序?在我们的CMS中,我们有一个使用jQuery可排序小部件的表单来对表单中的行进行排序。表单行最初是使用多维数组创建的。保存后,数据将保存在序列化数组中。因此,每当对行进行排序并保存时,数据都应按照已排序的顺序进行保存。我们遇到的问题是表单仍按原始数组的顺序输出,而不是保存的,排序后的数组。

How could I sort a defined array based on another array? In our CMS, we have a form that uses the jQuery sortable widget to sort the rows in the form. The form rows are initially created with a multidimensional array. Upon saving, the data is saved in a serialized array. So whenever you sort the rows and save, the data is saved in that "sorted" order, which is how it should be. The problem we're hitting is the form is still output in the order from the original array, not the saved, sorted array.

是否有一种方法可以对

以下是原始数组和顺序的外观:

Here's how the original array and order looks:

Array ( [group-1] => Array ( [fields] => Array ( [name] => Array ( [type] => text [name] => Full Name ) [email-address] => Array ( [type] => text [name] => Email Address ) ) ) [group-2] => Array ( [fields] => Array ( [address] => Array ( [type] => text [name] => Address ) ) ) [group-3] => Array ( [fields] => Array ( [city] => Array ( [type] => text [name] => City ) [zip] => Array ( [type] => text [name] => Zip ) ) ) )

这是排序后的保存数据

Array ( [group-3] => Array ( [city] => Apples [zip] => 12345 ) [group-1] => Array ( [name] => Tigre Woodrow [email-address] => email@email ) [group-2] => Array ( [address] => 1234 Anywhere Street ) )

因此从数组中,字段的行就是其中的组ID。

So from the arrays, the rows of fields are the group id's there. Would there be a way to sort based on that group id?

推荐答案

下面的注释在usort文档中听起来似乎可以为您提供帮助。我将尝试尽快针对您的问题更新代码,但它可能会将您推向正确的方向。

The below comment in the usort documentation sounds like it might help you out. I'll try to update the code soon specific to your problem but it might push you in the right direction.

如果要排序一个数组根据另一个充当优先级列表的数组,可以使用此函数。

If you want to sort an array according to another array acting as a priority list, you can use this function. <?php function listcmp($a, $b) { global $order; foreach($order as $key => $value) { if($a==$value) { return 0; break; } if($b==$value) { return 1; break; } } } $order[0] = "first"; $order[1] = "second"; $order[2] = "third"; $array[0] = "second"; $array[1] = "first"; $array[2] = "third"; $array[3] = "fourth"; $array[4] = "second"; $array[5] = "first"; $array[6] = "second"; usort($array, "listcmp"); print_r($array); ?>

更多推荐

PHP用另一个数组对多维数组进行排序

本文发布于:2023-11-30 10:03:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649592.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   多维   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!