如何从主数组构造子数组

时间:2012-09-03 11:16:55

标签: php arrays multidimensional-array

我想根据数据从多维数组构造子数n个数组。例如:我有一个主数组

    Array
    (
    [0] => Array
        (
            [id] => 1
            [status] => -1
        )

    [1] => Array
        (
            [id] => 2
            [status] => 1
        )

    [2] => Array
        (
            [id] => 3
            [status] => 2
        )

    [3] => Array
        (
            [id] => 4
            [status] => 2
        )
    [4] => Array
        (
            [id] => 5
            [status] => 2
        )
)

我想从这个数组得到3个数组取决于no和类型的状态值 像

  array{
    [0]=array(
        [status]=-1
        [count]=1

    )
    [1]=array(
        [status]=1
        [count]=1

    )
    [2]=array(
        [status]=2
        [count]=3

    )

}

提前致谢,

Sunil Kumar P

1 个答案:

答案 0 :(得分:0)

你的意思是这样的?:

$array = array(
    array('id' => 1, 'status' => -1),
    array('id' => 2, 'status' => 1),
    array('id' => 3, 'status' => 2),
    array('id' => 4, 'status' => 2),
    array('id' => 5, 'status' => 2)
);


$statuses = array();
foreach($array as $one){
    if(!isset($statuses[$one['status']])){ $statuses[$one['status']] = 0; }
    $statuses[$one['status']]++;
}

$newArray = array();
foreach($statuses as $key => $val){
    $newArray[] = array('status' => $key, 'count' => $val);
}

print_r($newArray);


/*Array
(
    [0] => Array
        (
            [status] => -1
            [count] => 1
        )

    [1] => Array
        (
            [status] => 1
            [count] => 1
        )

    [2] => Array
        (
            [status] => 2
            [count] => 3
        )

)*/