Array pointer & lt ;? Php $ arr & nbsp; array (id & gt; 1, title & gt; Test 1,), array (id & gt; 2, title & gt; test 2,), array (id & gt; 3, title & gt; test 3,), array (I array pointer problem
$ Arr = array (
Array (
'Id' => 1,
'Title' => 'test 1 ',
),
Array (
'Id' => 2,
'Title' => 'test 2 ',
),
Array (
'Id' => 3,
'Title' => 'test 3 ',
),
Array (
'Id' => 4,
'Title' => 'test 4 ',
),
Array (
'Id' => 5,
'Title' => 'test 5 ',
),
);
While (list ($ k, $ v) = each ($ arr )){
Print_r (current ($ arr ));
Echo'
';
}
Loop a two-dimensional array and use current to return the current element. Why does it start with 2nd elements? If you want to start from 1, please advise
Share to: 1, 'title' => 'test 1',), array ('id' => 2, 'title' => 'test 2... 'data-pics = ''>
------ Solution --------------------
When you first execute the while (list ($ k, $ v) = each ($ arr) here (note: each -- returns the current key/value pair in the array and moves the array pointer one step forward)
That is to say, each ($ arr) has moved the pointer of $ arr array one by one.
So it starts with 2nd elements.
Let's start with the first one:
Do
{
Print_r (current ($ arr ));
Echo'
';
}
While (list ($ k, $ v) = each ($ arr ));
Hope to help you.
------ Solution --------------------
The current function returns the current array unit... During the first while judgment, each has pointed the array unit to the next position .. As a result, the Cup starts from 2.
------ Solution --------------------
Use do instead, because while is the pointer that previously moved one
$ Arr = array (
Array (
'Id' => 1,
'Title' => 'test 1 ',
),
Array (
'Id' => 2,
'Title' => 'test 2 ',
),
Array (
'Id' => 3,
'Title' => 'test 3 ',
),
Array (
'Id' => 4,
'Title' => 'test 4 ',
),
Array (
'Id' => 5,
'Title' => 'test 5 ',
),
);
Do {
Print_r (current ($ arr ));
Echo'
';
}
While (list ($ k, $ v) = each ($ arr ));
?>