根据每行内的嵌套关联键对多维数组的第一级进行排序

问题描述 投票:0回答:1

我想首先指出,我已经在 Stackoverflow 和互联网上浏览过,尽管它们有很多示例,但没有一个以这样的方式进行解释,让我了解如何转换代码以使用我的数组结构。

我相信我需要使用 uksort 或 uasort 函数之一,但对此也不确定。

我的数组如下所示。

Array
(
    [0] => Array
        (
            [Result] => Array
                (
                    [id] => 260
                    [event_id] => 72
                    [year] => 2010
                    [york_score] => 27
                    [york_points] => 0.0
                    [lancs_score] => 51
                    [lancs_points] => 4.0
                    [winner] => L
                    [confirmed] => Y
                    [updated] => 2010-05-01 16:10:03
                )

            [Event] => Array
                (
                    [id] => 72
                    [sport_id] => 25
                    [event_title] => 1st Team
                    [Sport] => Array
                        (
                            [id] => 25
                            [sport_title] => Netball
                        )

                )

        )

其中 [0] 表示继续。

我需要根据 [Event][Sport] 中找到的 sport_title 键对所有数组 [0,1,2,3,...] 进行排序

有谁知道如何创建排序功能来做到这一点?

如果我以后需要调整/更改代码以在我的网站上的其他地方工作,对该功能如何工作的一些解释也会很有帮助。

php arrays sorting multidimensional-array
1个回答
3
投票

其中

$array
是保存您在问题中发布的数组的数组的名称。

function sort_multi($item_1, $item_2)
{
   // strcmp looks at two strings and, based off the characters' and their order,
   // determines which one is numerically greater. When this function returns a
   // negative, for example, it means the first item it's comparing is less that the
   // second item (ef and eg, for example). The usort function then rearranges
   // the array based off these comparisons.
   return strcmp($item_1['Event']['Sport']['sport_title'], $item_2['Event']['Sport']['sport_title']);
}

usort($array, 'sort_multi');
© www.soinside.com 2019 - 2024. All rights reserved.