循环中的个别价值

时间:2013-03-17 22:49:35

标签: php arrays loops foreach

我正在运行一个循环:

$array = $_POST['d'];

foreach($array as $a){
    print_r($a);
}

$ array包含数组(数组的数量不同) 我得到了这个结果。我只是想知道如何在循环中单独调用这些值。例如:$ thing =循环中的methv值

Array ( 
   [1173627548] => Array ( 
     [num] => 1173627548 
     [methv] => dont know 
     [q1] => - 
     [q2] => - 
     [q3] => U 
     [q4] => - 
     [comm] => 
    ) 
) 

对不起,如果我不清楚

print_r($ array)显示:

Array ( [0] => Array ( [1173627548] => Array ( [num] => 1173627548 [methv] => dont know [q1] => - [q2] => - [q3] => U [q4] => - [comm] => ) ) [1] => Array ( [1182868902] => Array ( [num] => 1182868902 [methv] => dont know [q1] => - [q2] => - [q3] => U [q4] => - [comm] => ) ) ) Array ( [0] => Array ( [1173627548] => Array ( [num] => 1173627548 [methv] => dont know [q1] => - [q2] => - [q3] => U [q4] => - [comm] => ) ) [1] => Array ( [1182868902] => Array ( [num] => 1182868902 [methv] => dont know [q1] => - [q2] => - [q3] => U [q4] => - [comm] => ) ) ) 

注意:我现在在这个数组中有2个数组

2 个答案:

答案 0 :(得分:0)

对于调试,我建议一些粗略但可读的调试,如下所示:

function trace($a) { print "<pre>".var_export($a, 1)."</pre>"; }
// then you can do:
trace($array);

至于您的问题,您可以像下面这样访问methv键:$array[0][1173627548]['methv'](如果上面的跟踪是完整的$ array变量,则为$array[1173627548]['methv']

答案 1 :(得分:0)

我想你想在数组$a上循环,其中每个元素都是数组。

当你循环$ array时,有一个项目的信息是你说的那个:

Array ( 
   [1173627548] => Array ( 
     [num] => 1173627548 
     [methv] => dont know 
     [q1] => - 
     [q2] => - 
     [q3] => U 
     [q4] => - 
     [comm] => 
    ) 
) 

如果您想访问methv元素,则应执行以下操作:

foreach($array as $a){
    echo $a["methv"]; // this would access $array[ 1173627548 ][ "methv" ]
}

当foreach继续时,您将继续访问所有$array[ ][ "methv" ]值 希望它有所帮助。


根据您的评论显示print_r($array)

首先,让我缩进它,以便我们更好地了解数组:

    Array ( 
    [0] => Array ( 
    [1173627548] => Array ( 
        [num] => 1173627548 
        [methv] => dont know 
        [q1] => - 
        [q2] => - 
        [q3] => U 
        [q4] => - 
        [comm] => 
        )
      )
    [1] => Array ( 
     [1182868902] => Array ( 
        [num] => 1182868902 
        [methv] => dont know 
        [q1] => - 
        [q2] => - 
        [q3] => U 
        [q4] => - 
        [comm] => )
        )
)
 Array (
    [0] => Array (
    [1173627548] => Array ( 
        [num] => 1173627548 
        [methv] => dont know 
        [q1] => - 
        [q2] => - 
        [q3] => U 
        [q4] => - [comm] => 
        )
     )
    [1] => Array (
     [1182868902] => Array (
        [num] => 1182868902 
        [methv] => dont know 
        [q1] => - 
        [q2] => - 
        [q3] => U 
        [q4] => -
        [comm] => 
        )
    )
) 

我猜你打印两次,因为我们可以一个接一个地看到两个完全一致的数组。

如果您想获得[methv]项,您需要访问:

$array[ 0 ][ 1173627548 ][ "methv" ]
$array[ 1 ][ 1182868902 ][ "methv" ]

所以你可以做的是两次使用foreach

foreach ($array as $a) {
    foreach ($a as $v) {
        echo $v[ "methv" ];
    }
}