Programing

배열의 첫 번째 N 요소를 얻습니까?

lottogame 2020. 5. 15. 08:01
반응형

배열의 첫 번째 N 요소를 얻습니까?


이것을 달성하는 가장 좋은 방법은 무엇입니까?


사용 ) (array_slice를

다음은 PHP 매뉴얼 의 예입니다 : array_slice

$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

작은 문제 만 있습니다

배열 인덱스가 당신에게 의미가 있다면, 그것은 숫자 배열 인덱스를 array_slice재설정하고 재정렬 한다는 것을 기억하십시오 . 이를 피 하려면 플래그를 설정 해야합니다 . (4 번째 파라미터, 5.0.2부터 사용 가능).preserve_keystrue

예:

$output = array_slice($input, 2, 3, true);

산출:

array([3]=>'c', [4]=>'d', [5]=>'e');

array_slice 를 다음과 같이 사용할 수 있습니다 .

$sliced_array = array_slice($array,0,$N);

현재 순서대로? array_slice () 라고 말하고 싶습니다 . 내장 함수이기 때문에 N까지 증가하는 인덱스를 추적하면서 배열을 반복하는 것보다 빠릅니다.


array_slice () 는 가장 좋은 방법입니다. 다음은 그 예입니다.

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

첫 번째 N 요소를 가져 오고 배열에서 제거 하려는 경우 다음을 사용할 수 있습니다 array_splice()( "splice"의 'p'참고).

http://docs.php.net/manual/da/function.array-splice.php

그렇게 사용하십시오 : $array_without_n_elements = array_splice($old_array, 0, N)

참고 URL : https://stackoverflow.com/questions/3720096/get-the-first-n-elements-of-an-array

반응형