Aşağıdaki yapacak bir PHP işlevi vardır:
Cari indeks ve sonra da bulunuyor Bir belirtilen dizi değerini taşıyın:
- Varolan iki endeks arasındaki taşındı.
- İkinci bir indeks / değer ile takas.
Ben görev için aşağıda sınıfı yapılmış, ancak PHP kütüphanede önceden varolan bir fonksiyon olup olmadığını merak?
Burada görev için oluşturduğunuz sınıfı:
class Rearranger
{
/*
* Determines how to move the specified value.
*/
public static function go($list, $indexToMove, $offset)
{
if(($offset == ($indexToMove - 1)) || ($offset == ($indexToMove + 1))) {
//Value is only being moved up or down one index, so just swap the values
$list = self::swap($list, $indexToMove, $offset);
} else if($offset < $indexToMove) {
//Value is being moved up (will be changing to a lower value index)
$list = self::move($list, $indexToMove, $offset);
} else if($offset > $indexToMove) {
//Value will be moving down (will be changing to a higher value index)
$list = self::move($list, $indexToMove, $offset - 1);
}
return $list;
}
/*
* Moves the value at $list[$indexToMove] in between
* $list[$offset - 1] and $list[$offset].
*/
public static function move($list, $indexToMove, $offset)
{
$container = $list[$indexToMove];
unset($list[$indexToMove]);
$list = array_values($list);
$list2 = array_slice($list, $offset);
$list = array_slice($list, 0, $offset);
array_push($list, $container);
return array_merge($list, $list2);
}
//Swap the values of two array indices
public static function swap($list, $indexA, $indexB)
{
$vA = $list[$indexA];
$vB = $list[$indexB];
$list[$indexA] = $vB;
$list[$indexB] = $vA;
return $list;
}
}
İşte Rearranger sınıfının bazı örnek kullanımları şunlardır:
$a1 = array('a', 'b', 'c', 'd', 'e', 'f');
function display($list) { echo '<p>' . var_dump($list) . '</p>'; }
//Move value at index 4 to between index 0 and 1
$a1 = Rearranger::go($a1, 4, 1);
display($a1);
//Move value at index 1 to between index 3 and 4
$a1 = Rearranger::go($a1, 1, 4);
display($a1);
//Swap value 2 and 3
$a1 = Rearranger::go($a1, 2, 3);
display($a1);
//Swap value 5 and 4
$a1 = Rearranger::go($a1, 5, 4);
display($a1);
//Do nothing
$a1 = Rearranger::go($a1, 2, 2);
display($a1);