@names = @kings[2,4,1]
In this case we use the @ prefix of the array and provide several indexes. If you are familiar with arrays in Perl, you surely remember that when we talk about the whole array we put @ in front of the name, but when we talk about a single element of an array we replace the @ sigil by the $ sigil and put square brackets at the end.
When we want create a list of one or more of the elements of the array we use the @ sigil again, as it represents «plural» and then we put one or more indexes in the square brackets after the name of the array.
See the full example here:
examples/array_slice.pl
use strict; use warnings; use 5.010; my @kings = ('Baldwin', 'Melisende', 'Fulk', 'Amalric', 'Guy', 'Conrad'); my @names = ($kings[2], $kings[4], $kings[1]); say join ', ', @names; # Fulk, Guy, Melisende my @slice = @kings[2,4,1]; say join ', ', @slice; # Fulk, Guy, Melisende
Scalar value @kings[2] better written as $kings[2]
This warning will appear if you try to use an array slice with a single index as in this example:
my @s = @kings[2];
This is how splain explains the warning:
Scalar value @kings[2] better written as $kings[2] at array_slice.pl line 14 (#1) (W syntax) You've used an array slice (indicated by @) to select a single element of an array. Generally it's better to ask for a scalar value (indicated by $). The difference is that $foo[&bar] always behaves like a scalar, both when assigning to it and when evaluating its argument, while @foo[&bar] behaves like a list when you assign to it, and provides a list context to its subscript, which can do weird things if you're expecting only one subscript. On the other hand, if you were actually hoping to treat the array element as a list, you need to look into how references work, because Perl will not magically convert between scalars and lists for you. See perlref.
If you would like to create a new array using a single element of another array then you should probably write:
my @s = $kings[2];
or if you want to make sure readers of your code won’t be surprised by the assignment of a scalar to an array, then you can even put parentheses around the value.
my @s = ($kings[2]);
Slice of an array reference
If we have out data in an ARRAY reference and not in an array, the code will be a bit more complex:
In this case we have a variable called $kings which is a reference to an array.
In the plain version, when we use individual elements we just need to dereference the ARRAY reference for each individual element.
my @names = ($kings->[2], $kings->[4], $kings->[1]);
If we would like to use the array slice syntax then first we need to dereference the whole array putting the @ sigil in-front of the reference: @$kings, but then we can simply put the square brackets behind that construct: my @slice = @$kings[2,4,1]; though I think I prefer the version when we put curly braces around the reference, thereby making it clear that it is a single unit of expression:
my @slice = @{$kings}[2,4,1];
The full example can be seen here:
examples/array_ref_slice.pl
use strict; use warnings; use 5.010; my $kings = ['Baldwin', 'Melisende', 'Fulk', 'Amalric', 'Guy', 'Conrad']; my @names = ($kings->[2], $kings->[4], $kings->[1]); say join ', ', @names; # Fulk, Guy, Melisende my @slice = @{$kings}[2,4,1]; say join ', ', @slice; # Fulk, Guy, Melisende
perlmaven.com
Use unset() to delete a associative array.
Ex:
<?php
.
span>] = array ('qty' => 1,
'desc' => 'Chaise bercante 10"',
'avail' => 10);
&.
s="keyword">=> 'Divan brun laitte"',
'avail' => 10);
if (isset($item['chaise'])) {
++$item
sp;
unset($item['divan']);
foreach ($item as $s) {
echo "<br />Commande " .
span>$s['qty'] . " " . $s['desc'];
}
?>
php.svchat.ru
Иногда нужно работать с диапазоном элементов массива. Например, нужно обрабатывать большой кусок массива или упорядочить массив, а затем извлечь из него «10 первых» значений от начала массива.
В данном уроке разбирается функция PHP array_slice()
, с помощью которой можно извлечь диапазон элементов из массива.
Основы использования array_slice()
В функцию array_slice()
передаются следующие аргументы:
- Массив, из которого будет извлекаться часть элементов.
- Позиция, с которой начинается извлекаемая часть массива (отсчёт элементов в массиве начинается с
0
).
- Количесвто элементов/, которые надо извлечь из массива.
array_slice()
возвращает массив, который содержит извлечённые элементы. Оригинальный массив остаётся без изменений.
Пример использования функции array_slice()
:
$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ); // Выводит "Array ( [0] => Stanley Kubrick [1] => Martin Scorsese )" print_r( array_slice( $directors, 1, 2 ) );
В выше приведённом коде создаётся массив с 4-мя элементами (имена режиссёров), затем используется функция array_slice()
для извлечения второго и третьего элементов.
Заметьте, что позиция элемента в массиве и его индекс не всегда одно и тоже. Например, первый элемент массива всегда имеет позицию 0
, но его индекс может быть 456
. Индексированные массивы PHP не обязаны иметь последовательные индексы, начинающиеся с ноля (хотя очень часто разработчики устанавливают именно такую нумерацию индекса).
Сохранение индексов
В выше приведённом примере можно заметить, что array_slice()
изменила индексы элементов в возвращаемом массиве: Stanley Kubrick
получил индекс 0
, а Martin Scorsese
получил индекс 1
. Часто такое функционирование не вызывает никаких проблем, так как важен порядок следования элементов в получаемом массиве, а не их индексы.
Однако, иногда важно сохранять индексы извлекаемых элементов. Например, индексы могут быть ключами, с помощью которых указываются записи в таблице данных, или они могут быть важными для каких-то других целей. В таком случае вы можете сохранить индексы извлекаемых элементов с помощью передачи в качестве четвёртого аргумента значения true
в функцию array_slice()
. Например:
$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ); // Выводит "Array ( [1] => Stanley Kubrick [2] => Martin Scorsese )" print_r( array_slice( $directors, 1, 2, true ) );
Заметьте, что функция array_slice()
в данном случае сохранили индексы оригинального массива для элементов: 1
для Stanley Kubrick
, и 2
для Martin Scorsese
.
Функция array_slice()
всегда сохраняет индексы в ассоциированных массивах. Таким образом нет необходимости передавать значение true
в качестве четвёртого аргумента при работе с ассоциированными массивами.
Извлечение элементов до конца массива
Если вы не будете указывать третий аргумент функции array_slice()
, то в массив -результат попадут все элементы оригинального массива, начиная со стартовой позиции до конца массива. Такое функционирование может быть удобно в случае, если вы не знаете размеров оригинального массива. Например:
$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ); // Выводит "Array ( [0] => Stanley Kubrick [1] => Martin Scorsese [2] => Fritz Lang )" print_r( array_slice( $directors, 1 ) );
Использование функции array_slice()
для ассоциированных массивов
вы можете использовать array_slice()
для извлечения элементов из ассоциированного массива. Ниже приведён пример извлечения 2 элементов из ассоциированного массива, начиная со второго элемента:
$movie = array( "title" => "Rear Window", "director" => "Alfred Hitchcock", "year" => 1954, "minutes" => 112 ); // Выводит "Array ( [director] => Alfred Hitchcock [year] => 1954 )" print_r( array_slice( $movie, 1, 2 ) );
Заметьте, что функция array_slice()
сохранила индексы "director"
и "year"
в массиве-результате.
Резюме
В данной статье мы разобрали использование функции array_slice()
. Полезной PHP функции, которая возвращает диапазон элементов массива. Вы узнали:
- Как использовать функцию
array_slice()
с индексированными и ассоциированными массивами.
- Сохранять оригинальные индексы при работе с индексированными массивами.
- Извлекать все элементы до конца оригинального массива.
ruseller.com
Use unset() to delete a associative array.
Ex:
<?php
$item['chaise'] = array ('qty' => 1,
'desc' => 'Chaise bercante 10"',
'avail' => 10);
$item['divan'] = array ('qty' => 1,
'desc' => 'Divan brun laitte"',
'avail' => 10);
if (isset($item['chaise'])) {
++$item['chaise']['qty'];
}
unset($item['divan']);
foreach ($item as $s) {
echo "<br />Commande " . $s['qty'] . " " . $s['desc'];
}
?>
php.net
Синтаксис
arr.slice([begin[, end]])
параметры
-
begin
Необязательный
- Нулевой индекс, на котором начнется извлечение.
- Можно использовать отрицательный индекс, указывающий смещение от конца последовательности.
slice(-2)
извлекает последние два элемента в последовательности.
- Если
begin
undefined, slice
начинается с индекса 0
.
- Если
begin
больше длины последовательности, возвращается пустой массив.
-
end
Дополнительно
- Индекс, основанный на нулевом значении, до которого заканчивается извлечение. вырезки
slice
до end
но не включая end
.
- Например,
slice(1,4)
извлекает второй элемент через четвертый элемент (элементы, индексированные 1, 2 и 3).
- Можно использовать отрицательный индекс, указывающий смещение от конца последовательности.
slice(2,-1)
извлекает третий элемент через второй-последний элемент в последовательности.
- Если
end
опущен, slice
извлекается через конец последовательности ( arr.length
).
- Если
end
больше длины последовательности, slice
извлекается до конца последовательности ( arr.length
).
Возвращаемое значение
Новый массив, содержащий извлеченные элементы.
Описание
slice
не изменяет исходный массив. Он возвращает неглубокую копию элементов из исходного массива. Элементы исходного массива копируются в возвращаемый массив следующим образом:
- Для ссылок на объекты (а не на фактический объект)
slice
копирует ссылки на объекты в новый массив. И исходный, и новый массив относятся к одному и тому же объекту. Если объект, на который ссылается, изменяется, изменения видны как для нового, так и для оригинального массива.
- Для строк, чисел и булевых (не
String
, Number
и Boolean
объектов) slice
копирует значения в новый массив. Изменения в строке, числе или булевых в одном массиве не влияют на другой массив.
Если новый элемент добавляется в любой массив, другой массив не влияет.
Примеры
Возвращает часть существующего массива
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; var citrus = fruits.slice(1, 3); // fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] // citrus contains ['Orange','Lemon']
Использование slice
В следующем примере slice
создает новый массив newCar
из myCar
. Оба включают ссылку на объект myHonda
. Когда цвет myHonda
изменен на фиолетовый, оба массива отражают изменение.
// Using slice, create newCar from myCar. var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }; var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']; var newCar = myCar.slice(0, 2); // Display the values of myCar, newCar, and the color of myHonda // referenced from both arrays. console.log('myCar = ' + JSON.stringify(myCar)); console.log('newCar = ' + JSON.stringify(newCar)); console.log('myCar[0].color = ' + myCar[0].color); console.log('newCar[0].color = ' + newCar[0].color); // Change the color of myHonda. myHonda.color = 'purple'; console.log('The new color of my Honda is ' + myHonda.color); // Display the color of myHonda referenced from both arrays. console.log('myCar[0].color = ' + myCar[0].color); console.log('newCar[0].color = ' + newCar[0].color);
Этот скрипт пишет:
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2, 'cherry condition', 'purchased 1997'] newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2] myCar[0].color = red newCar[0].color = red The new color of my Honda is purple myCar[0].color = purple newCar[0].color = purple
Массивные объекты
slice
метод также можно вызвать для преобразования Array-подобных объектов / коллекций в новый массив. Вы просто привязываете метод к объекту. arguments
внутри функции являются примером «объекта, подобного массиву».
function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3]
Связывание может быть выполнено с помощью. call
функции Function.prototype
и его также можно уменьшить, используя [].slice.call(arguments)
вместо Array.prototype.slice.call
. Во всяком случае, его можно упростить с помощью bind
.
var unboundSlice = Array.prototype.slice; var slice = Function.prototype.call.bind(unboundSlice); function list() { return slice(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3]
Упорядочение кросс-браузерного поведения
Хотя объекты-объекты (такие как объекты DOM) не требуются спецификацией для отслеживания поведения Mozilla при преобразовании с помощью Array.prototype.slice
и IE <9 этого не делают, версии IE, начиная с версии 9, позволяют это. «Shimming» может обеспечить надежное кросс-браузерное поведение. До тех пор, пока другие современные браузеры продолжают поддерживать эту способность, поскольку в настоящее время IE, Mozilla, Chrome, Safari и Opera, разработчики, читающие (DOM-поддерживающие) фрагмент кода, полагаясь на эту прокладку, не будут введены в заблуждение семантикой; они могут надежно полагаться на семантику, чтобы обеспечить теперь, по-видимому, фактическое стандартное поведение. (Прокладка также фиксирует IE для работы со вторым аргументом slice()
являющимся явным значением null
/ undefined
поскольку более ранние версии IE также не позволяли, но теперь все современные браузеры, включая IE> = 9).
/** * Shim for "fixing" IE's lack of support (IE < 9) for applying slice * on host objects like NamedNodeMap, NodeList, and HTMLCollection * (technically, since host objects have been implementation-dependent, * at least before ES2015, IE hasn't needed to work this way). * Also works on strings, fixes IE < 9 to allow an explicit undefined * for the 2nd argument (as in Firefox), and prevents errors when * called on other DOM objects. */ (function () { 'use strict'; var _slice = Array.prototype.slice; try { // Can't be used with DOM elements in IE < 9 _slice.call(document.documentElement); } catch (e) { // Fails in IE < 9 // This will work for genuine arrays, array-like objects, // NamedNodeMap (attributes, entities, notations), // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes), // and will not fail on other DOM objects (as do DOM elements in IE < 9) Array.prototype.slice = function(begin, end) { // IE < 9 gets unhappy with an undefined end argument end = (typeof end !== 'undefined') ? end : this.length; // For native Array objects, we use the native slice function if (Object.prototype.toString.call(this) === '[object Array]'){ return _slice.call(this, begin, end); } // For array like object we handle it ourselves. var i, cloned = [], size, len = this.length; // Handle negative value for "begin" var start = begin || 0; start = (start >= 0) ? start : Math.max(0, len + start); // Handle negative value for "end" var upTo = (typeof end == 'number') ? Math.min(end, len) : len; if (end < 0) { upTo = len + end; } // Actual expected size of the slice size = upTo - start; if (size > 0) { cloned = new Array(size); if (this.charAt) { for (i = 0; i < size; i++) { cloned[i] = this.charAt(start + i); } } else { for (i = 0; i < size; i++) { cloned[i] = this[start + i]; } } } return cloned; }; } }());
code.i-harness.com
Syntax
arr.slice([begin[, end]])
Parameters
begin
Optional
- Zero-based index at which to begin extraction.
- A negative index can be used, indicating an offset from the end of the sequence.
slice(-2)
extracts the last two elements in the sequence.
- If
begin
is undefined, slice
begins from index 0
.
- If
begin
is greater than the length of the sequence, an empty array is returned.
end
Optional
- Zero-based index before which to end extraction.
slice
extracts up to but not including end
.
- For example,
slice(1,4)
extracts the second element through the fourth element (elements indexed 1, 2, and 3).
- A negative index can be used, indicating an offset from the end of the sequence.
slice(2,-1)
extracts the third element through the second-to-last element in the sequence.
- If
end
is omitted, slice
extracts through the end of the sequence (arr.length
).
- If
end
is greater than the length of the sequence, slice
extracts through to the end of the sequence (arr.length
).
Return value
A new array containing the extracted elements.
Description
slice
does not alter the original array. It returns a shallow copy of elements from the original array. Elements of the original array are copied into the returned array as follows:
- For object references (and not the actual object),
slice
copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
- For strings, numbers and booleans (not
String
, Number
and Boolean
objects), slice
copies the values into the new array. Changes to the string, number or boolean in one array do not affect the other array.
If a new element is added to either array, the other array is not affected.
Examples
Return a portion of an existing array
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; var citrus = fruits.slice(1, 3); // fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] // citrus contains ['Orange','Lemon']
Using slice
In the following example, slice
creates a new array, newCar
, from myCar
. Both include a reference to the object myHonda
. When the color of myHonda
is changed to purple, both arrays reflect the change.
// Using slice, create newCar from myCar. var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }; var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']; var newCar = myCar.slice(0, 2); // Display the values of myCar, newCar, and the color of myHonda // referenced from both arrays. console.log('myCar = ' + JSON.stringify(myCar)); console.log('newCar = ' + JSON.stringify(newCar)); console.log('myCar[0].color = ' + myCar[0].color); console.log('newCar[0].color = ' + newCar[0].color); // Change the color of myHonda. myHonda.color = 'purple'; console.log('The new color of my Honda is ' + myHonda.color); // Display the color of myHonda referenced from both arrays. console.log('myCar[0].color = ' + myCar[0].color); console.log('newCar[0].color = ' + newCar[0].color);
This script writes:
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2, 'cherry condition', 'purchased 1997'] newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2] myCar[0].color = red newCar[0].color = red The new color of my Honda is purple myCar[0].color = purple newCar[0].color = purple
Array-like objects
slice
method can also be called to convert Array-like objects / collections to a new Array. You just bind the method to the object. The arguments
inside a function is an example of an ‘array-like object’.
function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3]
Binding can be done with the .call
function of Function.prototype
and it can also be reduced using [].slice.call(arguments)
instead of Array.prototype.slice.call
. Anyway, it can be simplified using bind
.
var unboundSlice = Array.prototype.slice; var slice = Function.prototype.call.bind(unboundSlice); function list() { return slice(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3]
Streamlining cross-browser behavior
Although host objects (such as DOM objects) are not required by spec to follow the Mozilla behavior when converted by Array.prototype.slice
and IE < 9 does not do so, versions of IE starting with version 9 do allow this. “Shimming” it can allow reliable cross-browser behavior. As long as other modern browsers continue to support this ability, as currently do IE, Mozilla, Chrome, Safari, and Opera, developers reading (DOM-supporting) slice code relying on this shim will not be misled by the semantics; they can safely rely on the semantics to provide the now apparently de facto standard behavior. (The shim also fixes IE to work with the second argument of slice()
being an explicit null
/undefined
value as earlier versions of IE also did not allow but all modern browsers, including IE >= 9, now do.)
/** * Shim for "fixing" IE's lack of support (IE < 9) for applying slice * on host objects like NamedNodeMap, NodeList, and HTMLCollection * (technically, since host objects have been implementation-dependent, * at least before ES2015, IE hasn't needed to work this way). * Also works on strings, fixes IE < 9 to allow an explicit undefined * for the 2nd argument (as in Firefox), and prevents errors when * called on other DOM objects. */ (function () { 'use strict'; var _slice = Array.prototype.slice; try { // Can't be used with DOM elements in IE < 9 _slice.call(document.documentElement); } catch (e) { // Fails in IE < 9 // This will work for genuine arrays, array-like objects, // NamedNodeMap (attributes, entities, notations), // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes), // and will not fail on other DOM objects (as do DOM elements in IE < 9) Array.prototype.slice = function(begin, end) { // IE < 9 gets unhappy with an undefined end argument end = (typeof end !== 'undefined') ? end : this.length; // For native Array objects, we use the native slice function if (Object.prototype.toString.call(this) === '[object Array]'){ return _slice.call(this, begin, end); } // For array like object we handle it ourselves. var i, cloned = [], size, len = this.length; // Handle negative value for "begin" var start = begin || 0; start = (start >= 0) ? start : Math.max(0, len + start); // Handle negative value for "end" var upTo = (typeof end == 'number') ? Math.min(end, len) : len; if (end < 0) { upTo = len + end; } // Actual expected size of the slice size = upTo - start; if (size > 0) { cloned = new Array(size); if (this.charAt) { for (i = 0; i < size; i++) { cloned[i] = this.charAt(start + i); } } else { for (i = 0; i < size; i++) { cloned[i] = this[start + i]; } } } return cloned; }; } }());
Specifications
Specification |
Status |
Comment |
ECMAScript 3rd Edition (ECMA-262) |
Standard |
Initial definition. Implemented in JavaScript 1.2. |
ECMAScript 5.1 (ECMA-262) The definition of ‘Array.prototype.slice’ in that specification. |
Standard |
|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of ‘Array.prototype.slice’ in that specification. |
Standard |
|
ECMAScript Latest Draft (ECMA-262) The definition of ‘Array.prototype.slice’ in that specification. |
Draft |
|
developer.mozilla.org
Use unset() to delete a associative array.
Ex:
<?php
$item['chaise'] = array ('qty' => 1,
'desc' => 'Chaise bercante 10"',
'avail' => 10);
$item['divan'] = array ('qty' => 1,
'desc' => 'Divan brun laitte"',
'avail' => 10);
if (isset($item['chaise'])) {
++$item['chaise']['qty'];
}
unset($item['divan']);
foreach ($item as $s) {
echo "<br />Commande " . $s['qty'] . " " . $s['desc'];
}
?>
mirrors.segmentfault.com