Php next with key

Интерфейс Iterator

Интерфейс для внешних итераторов или объектов, которые могут повторять себя изнутри.

Обзор интерфейсов

Предопределённые итераторы

PHP уже предоставляет некоторые итераторы для многих ежедневных задач. Смотрите список итераторов SPL для более детальной информации.

Примеры

Пример #1 Основы использования

Этот пример демонстрирует в каком порядке вызываются методы, когда используется с итератором оператор foreach.

class myIterator implements Iterator private $position = 0 ;
private $array = array(
«firstelement» ,
«secondelement» ,
«lastelement» ,
);

public function __construct () $this -> position = 0 ;
>

public function rewind (): void var_dump ( __METHOD__ );
$this -> position = 0 ;
>

#[\ReturnTypeWillChange]
public function current () var_dump ( __METHOD__ );
return $this -> array [ $this -> position ];
>

#[\ReturnTypeWillChange]
public function key () var_dump ( __METHOD__ );
return $this -> position ;
>

public function next (): void var_dump ( __METHOD__ );
++ $this -> position ;
>

public function valid (): bool var_dump ( __METHOD__ );
return isset( $this -> array [ $this -> position ]);
>
>

foreach( $it as $key => $value ) var_dump ( $key , $value );
echo «\n» ;
>
?>

Результатом выполнения данного примера будет что-то подобное:

string(18) "myIterator::rewind" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(0) string(12) "firstelement" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(1) string(13) "secondelement" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(2) string(11) "lastelement" string(16) "myIterator::next" string(17) "myIterator::valid"

Смотрите также

User Contributed Notes 18 notes

Order of operations when using a foreach loop:

1. Before the first iteration of the loop, Iterator::rewind() is called.
2. Before each iteration of the loop, Iterator::valid() is called.
3a. It Iterator::valid() returns false, the loop is terminated.
3b. If Iterator::valid() returns true, Iterator::current() and
Iterator::key() are called.
4. The loop body is evaluated.
5. After each iteration of the loop, Iterator::next() is called and we repeat from step 2 above.

This is roughly equivalent to:

while ( $it -> valid ())
$key = $it -> key ();
$value = $it -> current ();

$it -> next ();
>
?>

The loop isn’t terminated until Iterator::valid() returns false or the body of the loop executes a break statement.

The only two methods that are always executed are Iterator::rewind() and Iterator::valid() (unless rewind throws an exception).

The Iterator::next() method need not return anything. It is defined as returning void. On the other hand, sometimes it is convenient for this method to return something, in which case you can do so if you want.

If your iterator is doing something expensive, like making a database query and iterating over the result set, the best place to make the query is probably in the Iterator::rewind() implementation.

In this case, the construction of the iterator itself can be cheap, and after construction you can continue to set the properties of the query all the way up to the beginning of the foreach loop since the
Iterator::rewind() method isn’t called until then.

Things to keep in mind when making a database result set iterator:

* Make sure you close your cursor or otherwise clean up any previous query at the top of the rewind method. Otherwise your code will break if the same iterator is used in two consecutive foreach loops when the first loop terminates with a break statement before all the results are iterated over.

* Make sure your rewind() implementation tries to grab the first result so that the subsequent call to valid() will know whether or not the result set is empty. I do this by explicitly calling next() from the end of my rewind() implementation.

* For things like result set iterators, there really isn’t always a «key» that you can return, unless you know you have a scalar primary key column in the query. Unfortunately, there will be cases where either the iterator doesn’t know the primary key column because it isn’t providing the query, the nature of the query is such that a primary key isn’t applicable, the iterator is iterating over a table that doesn’t have one, or the iterator is iterating over a table that has a compound primary key. In these cases, key() can return either:
the row index (based on a simple counter that you provide), or can simply return null.

Iterators can also be used to:

* iterate over the lines of a file or rows of a CSV file
* iterate over the characters of a string
* iterate over the tokens in an input stream
* iterate over the matches returned by an xpath expression
* iterate over the matches returned by a regexp
* iterate over the files in a folder
* etc.

RocketInABog’s seemingly trivial tIterator_array class has one huge problem (which just cost me a couple of hours).

Consider this example, using their class:
$values = [ ‘one’ , ‘two’ , ‘three’ ];
foreach ( $values as $v ) <>
$current = current ( $values );
// $current === ‘one’, as you would expect

$iterator = new tIterator_array ( $values );
foreach ( $iterator as $v ) <>
$current = $iterator -> current (); // do NOT use current($iterator) or key($iterator).
// $current === false, but why?
?>
The problem is that foreach resets arrays, but doesn’t call Iterator::rewind on objects!

I also think it’s a design mistake that foreach works with Iterator, but current(), key() and end() don’t — these iterate over the objects fields.

I just refactored some code to use an Iterator instead of an array, and it broke in several very unexpected ways because of these differences.

# — Here is an implementation of the Iterator interface for arrays
# which works with maps (key/value pairs)
# as well as traditional arrays
# (contiguous monotonically increasing indexes).
# Though it pretty much does what an array
# would normally do within foreach() loops,
# this class may be useful for using arrays
# with code that generically/only supports the
# Iterator interface.
# Another use of this class is to simply provide
# object methods with tightly controlling iteration of arrays.

class tIterator_array implements Iterator private $myArray ;

public function __construct ( $givenArray ) $this -> myArray = $givenArray ;
>
function rewind () return reset ( $this -> myArray );
>
function current () return current ( $this -> myArray );
>
function key () return key ( $this -> myArray );
>
function next () return next ( $this -> myArray );
>
function valid () return key ( $this -> myArray ) !== null ;
>
>

If you have a custom iterator that may throw an exception in it’s current() method, there is no way to catch the exception without breaking a foreach loop.

The following for loop allows you to skip elements for which $iterator->current() throws an exception, rather than breaking the loop.

for ( $iterator -> rewind (); $iterator -> valid (); $iterator -> next ()) try $value = $iterator -> current ();
> catch ( Exception $exception ) continue;
>

It’s important to note that following won’t work if you have null values.

function valid () var_dump ( __METHOD__ );
return isset( $this -> array [ $this -> position ]);
>
?>

Other examples have shown the following which won’t work if you have false values:

function valid () return $this -> current () !== false ;
>
?>

Instead use:

function valid () return array_key_exists ( $this -> array , $this -> position );
>
?>

Or the following if you do not store the position.

public function valid () return ! is_null ( key ( $this -> array ));
>
?>

So, playing around with iterators in PHP (coming from languages where I’m spoiled with generators to do things like this), I wrote a quick piece of code to give the Fibonacci sequence (to infinity, though only the first terms up to F_ <10>are output).

class Fibonacci implements Iterator <
private $previous = 1 ;
private $current = 0 ;
private $key = 0 ;

public function current () <
return $this -> current ;
>

public function key () <
return $this -> key ;
>

public function next () <
$newprevious = $this -> current ;
$this -> current += $this -> previous ;
$this -> previous = $newprevious ;
$this -> key ++;
>

public function rewind () <
$this -> previous = 1 ;
$this -> current = 0 ;
$this -> key = 0 ;
>

public function valid () <
return true ;
>
>

$seq = new Fibonacci ;
$i = 0 ;
foreach ( $seq as $f ) <
echo » $f \n» ;
if ( $i ++ === 10 ) break;
>
?>

Источник

how to get next and prev item on array with custom key in php

Now what I am working on is to search having a key value (XA127) the previous key and the next key and their value. Here below the code that generate the array:

$array_same_cat = array(); if($loop_arrows->have_posts())< while($loop_arrows->have_posts())< $loop_arrows->the_post(); $current_id = get_the_ID(); $this_prod_sku = get_post_meta( $current_id, '_sku', true ); $array_same_cat[$this_prod_sku] = esc_url(get_permalink(intval($this_prod_sku))); > > 

Added this With this foreach I found the exact position of my element. Now I have to find how to do prev and next.

foreach($array_same_cat as $ar) < if($ar == $array_same_cat[$current_sku])< echo 'found'; >> 

2 Answers 2

What i understand from your question:-

  1. You have array
  2. You have a key, which you want to search in array and then you need to find-out prev and next value after it

Now you can do it like below:-

 "value", "XA127" => "value2", "AT257" => "value3"); $search_key = 'XA127'; $keys_array = array_keys($array_same_cat);//get keys array from original array $get_search_value_key_from_value_array = array_search($search_key,$keys_array); // get index of given key inside keys array $prev_key = $keys_array[$get_search_value_key_from_value_array -1]; // get previous key based on searched key index $next_key = $keys_array[$get_search_value_key_from_value_array+1];// get next key based on searched key index echo "Current key = ".$search_key." and current value = ".$array_same_cat[$search_key]."\n"; echo "Next key = ".$next_key." and next value = ".$array_same_cat[$next_key]."\n"; echo "Prev key = ".$prev_key." and prev value = ".$array_same_cat[$prev_key]."\n"; 

Источник

Читайте также:  Jquery вызвать функцию php
Оцените статью