排列数组

时间:2011-10-04 05:27:00

标签: php arrays multidimensional-array

我有一个按类别排序的数组

Array
(
[0] => Array
    (
        [name] => JOHN
        [category] => abc
    )

[1] => Array
    (
        [name] => JOHN
        [category] => abc
    )

[2] => Array
    (
    [name] => JOHN
        [category] => abc
    )

[3] => Array
    (
        [name] => John6
        [category] => cvb
    )

[4] => Array
    (
        [name] => John6
        [category] => cvb
    )

[5] => Array
    (
        [name] => Outfit7
        [category] => cvb
    )

[6] => Array
    (
        [name] => John6
        [category] => cvb
    )

[7] => Array
    (
        [name] => Joh8
        [category] => fgh
    )

[8] => Array
    (
        [name] => JOHN
        [category] => fgh
    )

[9] => Array
    (
        [name] => John9
        [category] => fgh
    )

[10] => Array
    (
        [name] => JOHN
        [category] => fgh
    )

[11] => Array
    (
        [name] => John0
        [category] => fgh
    )

[12] => Array
    (
        [name] => Johny
        [category] => fgh
    )
)

现在我希望这个数组来自类别的深度多维数组意味着像:

Array
{
[abc] => Array
         {
            [0] => Array
                (
                    [name] => JOHN MOFFETT
                    [category] => abc
                )
            [1] => Array
                (
                    [name] => JOHN MOFFETT
                    [category] => abc
                )
            [2] => Array
                (
                    [name] => JOHN MOFFETT
                    [category] => abc
                )
         }
[cvb] => Array
         {
            [3] => Array
                (
                    [name] => John Miller
                    [category] => cvb
                )
            [4] => Array
                (
                    [name] => John Slater
                    [category] => cvb
                )
            [5] => Array
                (
                    [name] => Outfit7
                    [category] => cvb
                )
            [6] => Array
                (
                    [name] => John Slater
                    [category] => cvb
                )
         }
}

等等。直到现在尝试使用foreach循环和for循环的许多方法但没有成功。任何人都可以告诉我如何做到这一点?任何帮助将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

试试这个,

$ tmp ='';

$ new_Array = array();

foreach($category_array as $cat_id => $cat)
{
   $tmp = $cat['category'];  
   $new_array[$tmp][$cat_id] = $cat;
}

干杯!!

答案 1 :(得分:1)

谢谢,我正在搜索同样的事情。 Upvote Sent :)没有评论的声誉所以这样做。希望你不介意。