PHP에서 배열을 어떻게 재 인덱싱합니까?
다음 배열이 있는데 키를 뒤집기 위해 다시 색인을 작성하고 싶습니다 (이상적으로 1에서 시작).
현재 배열 ( 편집 : 배열은 실제로 다음과 같습니다) :
Array (
[2] => Object
(
[title] => Section
[linked] => 1
)
[1] => Object
(
[title] => Sub-Section
[linked] => 1
)
[0] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
어떻게해야합니까 :
Array (
[1] => Object
(
[title] => Section
[linked] => 1
)
[2] => Object
(
[title] => Sub-Section
[linked] => 1
)
[3] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
시작 색인을 0으로 다시 색인하려면 다음을 수행하십시오.
$iZero = array_values($arr);
한 번에 시작해야하는 경우 다음을 사용하십시오.
$iOne = array_combine(range(1, count($arr)), array_values($arr));
사용 된 기능에 대한 매뉴얼 페이지는 다음과 같습니다.
가장 좋은 방법은 다음과 같습니다 .
# Array
$array = array('tomato', '', 'apple', 'melon', 'cherry', '', '', 'banana');
그 반환
Array
(
[0] => tomato
[1] =>
[2] => apple
[3] => melon
[4] => cherry
[5] =>
[6] =>
[7] => banana
)
이것을함으로써
$array = array_values(array_filter($array));
당신은 이것을 얻습니다
Array
(
[0] => tomato
[1] => apple
[2] => melon
[3] => cherry
[4] => banana
)
설명
array_values()
: 입력 배열의 값을 반환하고 숫자로 색인합니다.
array_filter()
: 사용자 정의 기능 배열 요소 필터 (UDF 경우의 어느 것도 제공되지 않는다 , 입력 테이블의 모든 항목이 FALSE 값을 삭제할 것이다 .)
방금 당신도 할 수 있다는 것을 알았습니다
array_splice($ar, 0, 0);
다시 인덱싱이 수행되므로 원래 배열의 복사본으로 끝나지 않습니다.
색인을 다시 생성하는 이유는 무엇입니까? 색인에 1을 추가하십시오.
foreach ($array as $key => $val) {
echo $key + 1, '<br>';
}
질문이 명확해진 후 편집 : array_values
0에서 시작하여 색인을 재설정 할 수 있습니다. 그런 다음 인쇄 된 요소가 1에서 시작되도록하려면 위의 알고리즘을 사용할 수 있습니다.
글쎄, 최종 목표가 무엇이든간에 실제로 0 기반이 아닌 1 기반으로 배열을 수정할 필요는 없지만 Gumbo가 게시 한 것처럼 반복 시간에 배열을 처리 할 수 있다고 생각합니다.
그러나 귀하의 질문에 대답하기 위해이 함수는 모든 배열을 1 기반 버전으로 변환해야합니다
function convertToOneBased( $arr )
{
return array_combine( range( 1, count( $arr ) ), array_values( $arr ) );
}
편집하다
더 재사용 가능하고 유연한 기능이 있습니다. 원한다면
$arr = array( 'a', 'b', 'c' );
echo '<pre>';
print_r( reIndexArray( $arr ) );
print_r( reIndexArray( $arr, 1 ) );
print_r( reIndexArray( $arr, 2 ) );
print_r( reIndexArray( $arr, 10 ) );
print_r( reIndexArray( $arr, -10 ) );
echo '</pre>';
function reIndexArray( $arr, $startAt=0 )
{
return ( 0 == $startAt )
? array_values( $arr )
: array_combine( range( $startAt, count( $arr ) + ( $startAt - 1 ) ), array_values( $arr ) );
}
이것은 당신이 원하는 것을 할 것입니다 :
<?php
$array = array(2 => 'a', 1 => 'b', 0 => 'c');
array_unshift($array, false); // Add to the start of the array
$array = array_values($array); // Re-number
// Remove the first index so we start at 1
$array = array_slice($array, 1, count($array), true);
print_r($array); // Array ( [1] => a [2] => b [3] => c )
?>
보다 우아한 솔루션 :
$list = array_combine(range(1, count($list)), array_values($list));
새로운 배열이 다음과 같이 1의 인덱스로 시작하도록 배열을 다시 색인 할 수 있습니다.
$arr = array(
'2' => 'red',
'1' => 'green',
'0' => 'blue',
);
$arr1 = array_values($arr); // Reindex the array starting from 0.
array_unshift($arr1, ''); // Prepend a dummy element to the start of the array.
unset($arr1[0]); // Kill the dummy element.
print_r($arr);
print_r($arr1);
위의 출력은 다음과 같습니다.
Array
(
[2] => red
[1] => green
[0] => blue
)
Array
(
[1] => red
[2] => green
[3] => blue
)
1 기반 배열을 사용하려는 이유를 고려할 수도 있습니다. 제로 기반 배열 (비 연관 배열을 사용하는 경우)은 표준이며 UI로 출력하려면 UI에 출력 할 때 정수를 늘려 솔루션을 처리합니다.
배열의 1 기반 인덱서에 대해 생각할 때 응용 프로그램과 코드에서 일관성에 대해 생각하십시오.
@monowerker와 마찬가지로 객체 키를 사용하여 배열을 다시 색인화해야했습니다 ...
$new = array();
$old = array(
(object)array('id' => 123),
(object)array('id' => 456),
(object)array('id' => 789),
);
print_r($old);
array_walk($old, function($item, $key, &$reindexed_array) {
$reindexed_array[$item->id] = $item;
}, &$new);
print_r($new);
결과는 다음과 같습니다.
Array
(
[0] => stdClass Object
(
[id] => 123
)
[1] => stdClass Object
(
[id] => 456
)
[2] => stdClass Object
(
[id] => 789
)
)
Array
(
[123] => stdClass Object
(
[id] => 123
)
[456] => stdClass Object
(
[id] => 456
)
[789] => stdClass Object
(
[id] => 789
)
)
$tmp = array();
foreach (array_values($array) as $key => $value) {
$tmp[$key+1] = $value;
}
$array = $tmp;
배열을 재정렬하지 않으려면 다음을 수행하십시오.
$ array = array_reverse ($ array);
$ array = array_reverse ($ array);
The array_reverse is very fast and it reorders as it reverses. Someone else showed me this a long time ago. So I can't take credit for coming up with it. But it is very simple and fast.
duplicate removal and reindex an array:
<?php
$oldArray = array('0'=>'php','1'=>'java','2'=>'','3'=>'asp','4'=>'','5'=>'mysql');
//duplicate removal
$fillteredArray = array_filter($oldArray);
//reindexing actually happens here
$newArray = array_merge($filteredArray);
print_r($newArray);
?>
Similar to Nick's contribution, I came to the same solution for reindexing an array, but enhanced the function a little since from PHP version 5.4, it doesn't work because of passing variables by reference. Example reindexing function is then like this using use
keyword closure:
function indexArrayByElement($array, $element)
{
$arrayReindexed = [];
array_walk(
$array,
function ($item, $key) use (&$arrayReindexed, $element) {
$arrayReindexed[$item[$element]] = $item;
}
);
return $arrayReindexed;
}
Sorting is just a sort(), reindexing seems a bit silly but if it's needed this will do it. Though not in-place. Use array_walk() if you will do this in a bunch of places, just use a for-key-value loop if this is a one-time operation.
<?php
function reindex(&$item, $key, &$reindexedarr) {
$reindexedarr[$key+1] = $item;
}
$arr = Array (2 => 'c', 1 => 'b', 0 => 'a');
sort($arr);
$newarr = Array();
array_walk($arr, reindex, &$newarr);
$arr = $newarr;
print_r($arr); // Array ( [1] => a [2] => b [3] => c )
?>
Here's my own implementation. Keys in the input array will be renumbered with incrementing keys starting from $start_index.
function array_reindex($array, $start_index)
{
$array = array_values($array);
$zeros_array = array_fill(0, $start_index, null);
return array_slice(array_merge($zeros_array, $array), $start_index, null, true);
}
Simply do this:
<?php
array_push($array, '');
$array = array_reverse($array);
array_shift($array);
You can easily do it after use array_values() and array_filter() function together to remove empty array elements and reindex from an array in PHP.
array_filter() function The PHP array_filter() function remove empty array elements or values from an array in PHP. This will also remove blank, null, false, 0 (zero) values.
array_values() function The PHP array_values() function returns an array containing all the values of an array. The returned array will have numeric keys, starting at 0 and increase by 1.
Remove Empty Array Elements and Reindex
First let’s see the $stack array output :
<?php
$stack = array("PHP", "HTML", "CSS", "", "JavaScript", null, 0);
print_r($stack);
?>
Output:
Array
(
[0] => PHP
[1] => HTML
[2] => CSS
[3] =>
[4] => JavaScript
[5] =>
[6] => 0
)
In above output we want to remove blank, null, 0 (zero) values and then reindex array elements. Now we will use array_values() and array_filter() function together like in below example:
<?php
$stack = array("PHP", "HTML", "CSS", "", "JavaScript", null, 0);
print_r(array_values(array_filter($stack)));
?>
Output:
Array
(
[0] => PHP
[1] => HTML
[2] => CSS
[3] => JavaScript
)
If it's OK to make a new array it's this:
$result = array();
foreach ( $array as $key => $val )
$result[ $key+1 ] = $val;
If you need reversal in-place, you need to run backwards so you don't stomp on indexes that you need:
for ( $k = count($array) ; $k-- > 0 ; )
$result[ $k+1 ] = $result[ $k ];
unset( $array[0] ); // remove the "zero" element
참고URL : https://stackoverflow.com/questions/591094/how-do-you-reindex-an-array-in-php
'IT' 카테고리의 다른 글
C #을 사용하여 URL 매개 변수를 어떻게 디코딩합니까? (0) | 2020.06.23 |
---|---|
ipython 노트북에서 셀 실행 시간을 측정하는 간단한 방법 (0) | 2020.06.23 |
인 텐트로 SMS 응용 프로그램 시작 (0) | 2020.06.23 |
Gradle Sync가 제약 조건 레이아웃을 찾을 수 없습니다 : 1.0.0-alpha2 (0) | 2020.06.23 |
UITableView에서 구분 기호의 전체 너비를 설정하는 방법 (0) | 2020.06.23 |