0

i have an array like follows with a varying number of top level arrays:

Array
(
    [1534] => Array
        (
            [userid] => 1534
            [a1] => 3
            [a2] => 6
            [a3] => 5
            [groupID] => 2
            [total] => 109
        )

    [1535] => Array
        (
            [userid] => 1535
            [a1] => 6
            [a2] => 4
            [a3] => 1
            [groupID] => 2
            [total] => 125
        )
)

are there any options other than foreach, to get:

Array
{
    [userid] => Array
        (
            [1534] => 1534
            [1535] => 1535
        )

    [a1] => Array
        (
            [1534] => 3
            [1535] => 6
        )


    [a2] => Array
        (
            [1534] => 6
            [1535] => 4
        )


    [a3] => Array
        (
            [1534] => 5
            [1535] => 1
        )


    [groupID] => Array
        (
            [1534] => 2
            [1535] => 2
        )


    [total] => Array
        (
            [1534] => 109
            [1535] => 125
        )
)

? the purpose being to traverse through the new arrays for each row of a table in the output

2 Answers2

3

You dont need to change layout just to traverse it. It can be done without changing it.

$keys = array_keys(current($array));
$len = count($array);

foreach($keys as $key){
// Access the key first 
    for($i=0;$i<$len; $i++){
    // access the row later
        echo $array[$i][$key];
    }
}
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
1

are there any options other than foreach

Not really

Anything you want to do that looks like iteration means using for/foreach loop.

i.e. if you do need (note shiplu.mokadd.im's answer) to reformat the array you'll need some code like so:

$result = array();
foreach($input as $i => $row) {
    foreach($row as $key => $value) {
        $result[$key][$i] = $value;
    }
}
Community
  • 1
  • 1
AD7six
  • 63,116
  • 12
  • 91
  • 123