0

我需要通过变量“i_lastname”对这个多维 php 对象进行排序。

我用 usort 和 ksort 尝试了大多数示例,但无济于事。大多数例子都是这样的,但对我不起作用。

function sort_by_name($a, $b)
{
  return ($a->i_lastname < $b->i_lastname ? -1 : 1);
}
usort($cards, 'sort_by_name');

这是对象结构。

谢谢你。

Array
(
    [0] => Array
        (
            [officer_id] => 4D5DEF60
            [card_id] => 5
            [general] => Array
                (
                    [0] => Array
                        (
                            [i_officer_id] => 4D5DEF60
                            [i_officer_name] => 
                            [i_datetime] => 2012-06-12 13:47:00
                            [i_location] => 17 Rue de Neuch, Yvette, France
                            [i_lat] => 48.6955
                            [i_lon] => 2.21458
                            [i_reason] => DUI
                        )
                )
            [subject] => Array
                (
                    [0] => Array
                        (
                            [subject_id] => 6
                            [i_lastname] => Toro
                            [i_firstname] => Benicio
                        )
                    [1] => Array
                        (
                            [subject_id] => 9
                            [i_lastname] => Limon
                            [i_firstname] => Pedro
                        )
                )
            [vehicle] => Array
                (
                )
        )

    [1] => Array
        (
            [officer_id] => 4D5DEF60
            [card_id] => 2
            [general] => Array
                (
                    [0] => Array
                        (
                            [i_officer_id] => 0f3b45a3
                            [i_officer_name] => 
                            [i_datetime] => 2012-06-06 19:42:00
                            [i_location] => 10231 Yankee St, Miami, USA
                            [i_lat] => 39.5952
                            [i_lon] => -84.2003
                            [i_reason] => Speeding
                        )
                )
            [subject] => Array
                (
                    [0] => Array
                        (
                            [subject_id] => 3
                            [i_lastname] => Doe
                            [i_firstname] => John
                        )
                    [0] => Array
                        (
                            [subject_id] => 15
                            [i_lastname] => Doe
                            [i_firstname] => Jane
                        )
                )
            [vehicle] => Array
                (
                )
        )
)
4

1 回答 1

1

您应该使用['...']而不是->...- 您正在处理数组,而不是对象。

您的回调应如下所示:

return strnatcasecmp($a['i_lastname'],$b['i_lastname']);

任何strcmp, strcasecmp,strnatcmpstrnatcasecmp应该可以正常工作,您只需要决定哪一个最适合您正在做的事情。

于 2012-06-12T14:37:34.817 回答