按另一个参数数组对对象数组进行排序和分组

时间:2015-11-04 02:50:30

标签: php arrays sorting object

我希望通过一组级联规则按相似的类似对象属性对项目进行分组和排序,但我不确定如何去做。

让我们说我有一组看起来像这样的对象:

Array
(
    [0] => stdClass Object
    (
        [name] => New Name (phase 1)
    )
    [1] => stdClass Object
    (
        [name] => Test (original)
    )
    [2] => stdClass Object
    (
        [name] => Test (phase 3)
    )
    [3] => stdClass Object
    (
        [name] => Another Name (phase 1)
    )
    [4] => stdClass Object
    (
        [name] => Another Name (original)
    )
    [5] => stdClass Object
    (
        [name] => Test (phase 2)
    )
    [6] => stdClass Object
    (
        [name] => New Name
    )
)

我希望能够定义规则以对它们进行分组和排序,将组设置为主要父项的属性。规则如下:

如果名称没有括号的对象存在,则它应该是父对象。如果不存在,则名称中包含(原始)的对象应为父对象。如果不存在,则(阶段1)的对象应该是父对象,依此类推。排序名称的规则集如下:

No parentheses, (original), (phase 1), (phase 2), (phase 3)

理想情况下,我想最终得到这个对象:

Array
(
    [0] => stdClass Object
    (
        [name] => New Name
        [children] => Array (
            [0] => stdClass Object
            (
                [name] => New Name (phase 1)
            )
        )
    )    
    [1] => stdClass Object
    (
        [name] => Test (original)
        [children] => Array (
            [0] => stdClass Object
            (
                [name] => Test (phase 2)
            )
            [1] => stdClass Object
            (
                [name] => Test (phase 3)
            )
        )
    )
    [2] => stdClass Object
    (
        [name] => Another Name (original)
        [children] => Array (
            [0] => stdClass Object
            (
                [name] => Another Name (phase 1)
            )
        )  
    )
)

0 个答案:

没有答案