To convert foreach statements to for

How can you convert foreach -statements to for -loops in PHP?

Examples to be used in your answers

1

 foreach( $end_array[1]['tags'] as $tag )

and

2

 foreach($end_array as $question_id => $row2)

In both examples the expressions left to 'as' refer to an array. An array stores a mapping of keys to values. Both examples iterate through elements of this mapping.

In the first example you are only interested in the values (and not in the keys they are mapped to). At every iteration $tag refers to the "current" value.

In the second example $question_id refers to the key, $row2 refers to the value of the "current" mapping.

In general the expression

foreach($array as $key => $value) {
  ...
}

could be rewritten as

$keys = array_keys($array);
for($k=0; $k < count($keys); $k++) {
  $key = $keys[$k];
  $value = $array[$key];
  ...
}

转换后的代码有语法问题,请尝试以下操作(对于大型数组也可以更快地运行):

$keys = array_keys($array);
for ($k = 0, $key_size = count($keys); $k < $key_size; $k++) {
  $key = $keys[$k];
  $value = $array[$key];
  ...
}
链接地址: http://www.djcxy.com/p/58180.html

上一篇: =>和。之间的区别是什么?

下一篇: 将foreach语句转换为for