phparraysmultidimensional-array

Declare individual variables based on the key names in a 2d array


UPDATE: Sorry, I figured it out.. I'm only taking out $value[0], so of course its only one result. Need more sleep. Thanks alot. I'm still open for suggestions to a cleaner way to split arrays.

I have an array $tdata with this structure:

Array
(
    [] => Array
    (
        [0] => Array
            (
                [firstName] => test
                [lastName] => test
                [userName] => test@test.com
                [password] => test
                [course] => test
                [role] => test
            )

        [1] => Array
            (
                [firstName] => test
                [lastName] => test
                [userName] => test@test.com
                [password] => test
                [course] => test
                [role] => test
            )

    )

    [delete] => Array
    (
        [0] => Array
            (
                [firstName] => test
                [lastName] => test
                [userName] => test@test.com
                [password] => test
                [course] => test
                [role] => test
            )

    )

    [update] => Array
    (
        [0] => Array
            (
                [firstName] => test
                [lastName] => test
                [userName] => test@test.com
                [password] => test
                [course] => test
                [role] => test
            )

    )

    [outrole] => Array
    (
        [0] => Array
            (
                [firstName] => test
                [lastName] => test
                [userName] => test@test.com
                [password] => test
                [course] => test
                [role] => test
            )

    )

)

I am trying to split it up into smaller arrays. Like this:

foreach ($tdata as $key => $value) {

    if ($key == '') {
       $create[] = $value[0];
    }elseif ($key == 'outrole') {
       $outrole[]  = $value[0];
    }elseif ($key == 'delete') {
       $delete[] = $value[0];
    }elseif ($key == 'update') {
       $update[] = $value[0];
    }else{
     $noaction[] = $value[0];
    }

}

This way the array keeps overwriting itself, I think. print_r($create) or any other of the arrays always returns only 1 result. Can enlighten me and tell me what I am doing wrong?

If there is a better way to do it I would love to hear that as well.


Solution

  • If those keys are always present then you don't really need a loop:

    $create = $original['create'];
    $outrole = $original['outrole'];
    

    You can add a check if they are set:

    $create = isset($original['create']) ? $original['create'] : array();
    

    This will set it to a blank array if it's not present.