【发布时间】:2011-11-25 19:24:30
【问题描述】:
我有一个数据库表如下:
这会返回图片中的所有列标题,但最重要的是 slug 和 parent(不确定 id_button)。
数组由 id_button ASC 自动排序,这让我很恼火。但是,无论如何,这并不重要,因为我需要对它进行完全不同的排序,或者在填充数组后重新排序。
数组按 id_button 的顺序返回:
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
2 => array(
'id_button' => 3,
'parent' => 'google.com',
'position' => 'after',
'slug' => 'another_test',
),
3 => array(
'id_button' => 4,
'parent' => 'testing'
'position' => 'child_of',
'slug' => 'google.com',
)
);
我需要订购它,以便如果在任何parent 中找到slug,则需要先加载parent 中的slug,然后再加载在父级中定义的slug。
如果它直接在它之前并不重要。例如,您看到testing 是第一个返回的slug,但它的父级是最后一个 slug (google.com)。因此,只要对定义父项的 slug 行进行排序,使其位于父列中具有 slug 值的行之前,一切都很好。
所以在这种情况下,它可以重新排序为以下这 3 个有序数组中的任何一个:
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
2 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
3 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
)
);
或者这个...
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
2 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
3 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
)
);
或者甚至这个...
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
2 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
),
3 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
)
);
所有这 3 个有序数组都可以工作,因为与 parent 匹配的 slug 数组在匹配 parent 的数组之前,并且由于 slug 值,sub_test_1 不匹配任何在parent 值中,此数组顺序并不重要,因此该数组可以位于数组中的任何位置。
我该怎么做?我正在考虑以某种方式遍历数组并尝试确定蛞蝓是否在任何父母中,然后以某种方式重新排序......
简而言之,slug 需要在 parent 之前排序,前提是数组中存在与 slug 匹配的 parent。否则,如果找不到匹配项,则顺序不重要。
【问题讨论】:
-
通常解决这个问题的最好方法是尽可能将排序留给数据库。
-
如何通过数据库来完成?但是,因为数据库查询目前没有对任何内容进行排序,所以它仍然使用 id_button 以升序返回数组。
-
如何从那里获取数据?
-
另外,有人告诉我,如果您要抓取表格的全部内容,那么您应该使用
ORDER BY NULL,这样就不会有任何内存问题。所以我在桌子上使用这个顺序。 -
好吧,它不必返回与新订单相同的数组。它也可以返回具有新顺序的不同数组。因为我需要将有序数组传递给一个函数,所以如果有序数组是不同的名称,这不是问题。
标签: php sorting multidimensional-array