-5

I would like to construct sub n number of arrays from a multi dimensional array depends on the data. For example: I have a main array as

    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
        )
)

I would like to get 3 arrays from this array depends on the no and type of status value like

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

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

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

    )

}

Thanks in advance,

Sunil Kumar P

4
  • What have tried? What is your specific problem in using a loop?
    – feeela
    Sep 3, 2012 at 11:18
  • [0]=array( or [0]=>array( ?? typo ??
    – swapnesh
    Sep 3, 2012 at 11:19
  • @sunil not possible to keep same keys 0 for all three
    – swapnesh
    Sep 3, 2012 at 11:20
  • I am looking for a solution for an unlimited sub array result. I mean the no of sub arrays will be equal to the status types. Now there is only 3 status types like -1,1 and 2. If there is n no of status types, then we need to get n sub arrays having status type field and status count.... Sep 3, 2012 at 11:25

1 Answer 1

0

You mean like this?:

$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
        )

)*/
2
  • Thanks for your time . I mean I would like to construct a chart for the user status . So I would like to get the no of each user status. The main array contains all users , and I would like to get each user status and the count. Hope that you got the idea now. Thanks in advance Sep 3, 2012 at 11:30
  • what I made does exactly what you want .. I don't understand what more ? Sep 3, 2012 at 11:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.