基于内部数组的值重新排列多维数组

时间:2010-05-18 10:29:06

标签: php multidimensional-array

我有一个像这样的数组

Array
(
    [0] => Array
        (
            [cat_name] => Clothing
            [cat_id] => 1
            [item_name] => shirt
            [item_id] => 1
            [src] => 177
            [sic] => 78
        )

    [1] => Array
        (
            [cat_name] => Stationary
            [cat_id] => 3
            [item_name] => note book
            [item_id] => 8
            [src] => 50
            [sic] => 10
        )

    [2] => Array
        (
            [cat_name] => Stationary
            [cat_id] => 3
            [item_name] => ball pen
            [item_id] => 10
            [src] => 59
            [sic] => 58
        )

    [3] => Array
        (
            [cat_name] => Expandable
            [cat_id] => 4
            [item_name] => vim powder
            [item_id] => 14
            [src] => 34
            [sic] => 23
        )

    [4] => Array
        (
            [cat_name] => Clothing
            [cat_id] => 1
            [item_name] => pant
            [item_id] => 16
            [src] => 100
            [sic] => 10
        )

)

现在我想要什么 首先按cat_id排序,然后创建一个具有以下结构的新数组

Array
(
    [0] =>"Clothing"=>Array
        (

          [0]=>Array
            (
                [item_name] => shirt
                [item_id] => 1
                [src] => 177
                [sic] => 78
            )
          [1] => Array
            (
                [item_name] => pant
                [item_id] => 16
                [src] => 100
                [sic] => 10
            )

        )
    [1] => "Stationary"=>Array
        (
         [0] => Array
            (   
                [item_name] => note book
                [item_id] => 8
                [src] => 50
                [sic] => 10
            )

        [1] => Array
            (
                [item_name] => ball pen
                [item_id] => 10
                [src] => 59
                [sic] => 58
            )

        )
    [2]=>"Expandable => Array
        (
        [0] => Array
            (
                [item_name] => vim powder
                [item_id] => 14
                [src] => 34
                [sic] => 23
            )
        )
)

2 个答案:

答案 0 :(得分:4)

未测试

$output = array();
foreach($array as $item) {
    if(!isset($output[$item['cat_name']])) {
        $output[$item['cat_name']] = array();
    }
    $catName = $item['cat_name'];
    unset($item['cat_name']);
    $output[$catName][] = $item;
}

答案 1 :(得分:3)

function cmp($a, $b)
{
    if ($a['cat_id'] == $b['cat_id']) {
        return 0;
    }
    return ($a['cat_id'] < $b['cat_id']) ? -1 : 1;
}
// sort by cat_id 
usort($array, 'cmp');

// create the grouped array
$res = array();
foreach($array as &$item) {
    $cat_name = $item['cat_name'];
    unset($item['cat_name'], $item['cat_id']);
    $res[$cat_name][] = $item;
}