for-each循环中的=>运算符是什么意思?

Sol*_*ace 0 php foreach loops

我知道PHP中的=>运算符用于在关联数组中赋值:

$array = array(key1 => value1, key2 => value2, key3=> value3);
Run Code Online (Sandbox Code Playgroud)

我理解for-each loop在PHP中迭代就像

foreach ($array as $value) {
  echo $value;
}
Run Code Online (Sandbox Code Playgroud)

但我遇到过类似的事情

foreach ($question->get_order($qa) as $value => $ansid) {...}
Run Code Online (Sandbox Code Playgroud)

我不明白$value => $ansid它的一部分.

$question -> get_order($qa)返回一个数组.我们想要遍历它,所以它应该是foreach ($question -> get_order($qa) as $value) {...}?

Com*_*hip 5

的=>操作者分配阵列的左手侧上的可变的键和值,以在右手侧上的变量.例如,如果你是数组

$array = array(key1 => value1, key2 => value2, key3=> value3);

然后

foreach ($array as $key => $value) {
  echo "$key: $value\n";
}
Run Code Online (Sandbox Code Playgroud)

将打印

key1: value1
key2: value2
key3: value3
Run Code Online (Sandbox Code Playgroud)

如果您的数组键也有意义,并且在for-loop中需要它们,并且与值分开,则它特别有用.

例如:

$students_by_id = array( 1234 => "John Smith", 2372 => "Pete Johnson" );
$grades = array( 1234 => 87, 2372 => 68 );

foreach( $grades as $student_id => $grade ) {
  echo $students_by_id[$student_id] . " scored " . $grade . " / 100 points.\n";
}
Run Code Online (Sandbox Code Playgroud)

注意,如果数组是"非关联的",例如

$array = array( value1, value2, value3 );
Run Code Online (Sandbox Code Playgroud)

然后PHP将为您创建数字索引,并在其中创建$key变量

foreach ($array as $key => $value )
Run Code Online (Sandbox Code Playgroud)

将运行0,1,2,3,...,使你的循环有效地等效

for ($key = 0, $key < count($array); ++$key) {
  $value = $array[$key];
  // ...
}
Run Code Online (Sandbox Code Playgroud)

一般来说,我仍然会建议使用=>符号,如果不是为了提高效率,那么至少在列表中缺少索引或者你决定切换到关联数组之后.