0

我有一个如下数组,其中包含不同数量的顶级数组:

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

除了 foreach 之外,还有其他选择吗:

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

? 目的是遍历输出中表的每一行的新数组

4

2 回答 2

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];
    }
}
于 2013-01-19T19:00:24.953 回答
1

除了foreach还有其他选择吗

并不真地

你想做的任何看起来像迭代的事情都意味着使用 for/foreach 循环。

即,如果您确实需要(注意shiplu.mokadd.im 的回答)重新格式化数组,您将需要一些如下代码:

$result = array();
foreach($input as $i => $row) {
    foreach($row as $key => $value) {
        $result[$key][$i] = $value;
    }
}
于 2013-01-19T19:04:51.917 回答