developer tip

foreach 목록 항목의 역순

optionbox 2020. 10. 31. 09:36
반응형

foreach 목록 항목의 역순


이 코드의 목록 항목 순서를 바꾸고 싶습니다. 기본적으로 가장 오래된 것에서 최근으로가는 일련의 연도이며 나는 그 결과를 되돌리려 고 노력하고 있습니다.

<?php
    $j=1;     
    foreach ( $skills_nav as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
    }
?>  

뒤로 걷기

순수 PHP 솔루션을 찾고 있다면 목록을 거꾸로 세어 앞뒤로 액세스 할 수도 있습니다.

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

$index = count($accounts);

while($index) {
  echo sprintf("<li>%s</li>", $accounts[--$index]);
}

위의 $index내용은 총 요소 수로 설정 한 다음 요소에 대한 액세스를 처음부터 끝까지 시작하여 다음 반복의 인덱스 값을 줄입니다.

어레이 반전

또한 array_reverse함수활용 하여 배열의 값을 반전하여 역순으로 액세스 할 수 있습니다.

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

foreach ( array_reverse($accounts) as $account ) {
  echo sprintf("<li>%s</li>", $account);
}

또는 array_reverse 함수를 사용할 수 있습니다 .


array_reverse()소스 배열을 변경하지 않지만 새 배열을 반환합니다. (참조 array_reverse()) 따라서 먼저 새 배열을 저장하거나 for 루프 선언 내에서 함수를 사용해야합니다.

<?php 
    $input = array('a', 'b', 'c');
    foreach (array_reverse($input) as $value) {
        echo $value."\n";
    }
?>

출력은 다음과 같습니다.

c
b
a

따라서 OP에 주소를 지정하는 코드는 다음과 같습니다.

<?php
    $j=1;     
    foreach ( array_reverse($skills_nav) as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
}

마지막으로, $j는 역방향 워크를 얻기위한 초기 시도에 사용 된 카운터 $skills_nav이거나 $skills_nav배열 을 계산하는 방법 이라고 추측 할 것 입니다. 전자의 경우 올바른 솔루션이 있으므로 지금 제거해야합니다. 후자의 경우 루프 외부에서 $j = count($skills_nav).


배열 (또는 임시 복사본)을 파괴해도 괜찮다면 다음을 수행 할 수 있습니다.

$stack = array("orange", "banana", "apple", "raspberry");

while ($fruit = array_pop($stack)){
    echo $fruit . "\n<br>"; 
}

생성 :

raspberry 
apple 
banana 
orange 

I think this solution reads cleaner than fiddling with an index and you are less likely to introduce index handling mistakes, but the problem with it is that your code will likely take slightly longer to run if you have to create a temporary copy of the array first. Fiddling with an index is likely to run faster, and it may also come in handy if you actually need to reference the index, as in:

$stack = array("orange", "banana", "apple", "raspberry");
$index = count($stack) - 1;
while($index > -1){
    echo $stack[$index] ." is in position ". $index . "\n<br>";
    $index--;
} 

But as you can see, you have to be very careful with the index...


You can use usort function to create own sorting rules


Assuming you just need to reverse an indexed array (not associative or multidimensional) a simple for loop would suffice:

$fruits = ['bananas', 'apples', 'pears'];
for($i = count($fruits)-1; $i >= 0; $i--) {
    echo $fruits[$i] . '<br>';
} 

If your array is populated through an SQL Query consider reversing the result in MySQL, ie :

SELECT * FROM model_input order by creation_date desc

<?php
    $j=1; 


      array_reverse($skills_nav);   


    foreach ( $skills_nav as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
    }
?> 

참고URL : https://stackoverflow.com/questions/10777597/reverse-order-of-foreach-list-items

반응형