2012-09-22 5 views
0
foreach ($this->parent->get_sections(null, $this->parent->author) as $section) 
{ 
    //... 
} 

내가하려는 것은 루프를 각각 원하는대로 순서대로 출력하도록한다. 각 $section의 이름은 $section->name으로 검색 할 수 있습니다. $section "Section 2"를 먼저 출력 한 다음 "Section 1"(foreach 순으로 출력하지 않음)을 출력한다고 가정 해 봅시다. 어떻게 그렇게 할 수 있습니까? 매번 섹션 이름을 확인하는 경우 for 루프가 적절한 방법이라고 가정합니다.foreach를 PHP로 변환하기

답변

1

코드 구조를 알지 못해서, 나는 비슷한 것을 할 것입니다.

// Get Org Sections 
$sections = $this->parent->get_sections(null, $this->parent->author); 

// Loop thru sections to get an array of names 
foreach ($sections as $key=>$section) 
{ 
$sorted_sections[$section->name] = $key; 
} 

// Sort Array 
//ksort — Sort an array by key 
//krsort — Sort an array by key in reverse order 
krsort($sorted_sections); 

foreach ($sorted_sections as $section) 
{ 
// Orig Code 
} 
1
$section = $this->parent->get_sections(null, $this->parent->author); 
    echo $section[2]->name; 
    echo $section[1]->name;//just output the indexes the way you want 

당신이 말 내림차순으로 정렬 된 원한다면, 당신이 그런 식으로 분류하고 표시 할 for 루프를 사용할 수 있습니다.

+0

정보 주셔서 감사합니다! – globetrotter

4

parent->get_sections()을 호출 할 때 적절한 결과가 표시됩니다. 어떻게 할 것인가는 전적으로 그 클래스와 메소드의 구현에 달려 있습니다. 정렬을 위해 foreachfor으로 변경하면 코드 냄새가 나는 것처럼 보입니다.


가능한 한 기술적 인 질문에 답하십시오. 이 섹션의 특정 번호를 인식하지 특히 ​​경우

$sections = $this->parent->get_sections(null, $this->parent->author); 
$num_sections = count($sections); 
for ($i = 0; $i < $num_sections; $i++) { 
    // what you do here is up to you $sections[$i] 
} 
+0

고마워, 코드 냄새 같은 것 같지만 불행히도 플러그인은 개략적인데 나는 더러운 수정이 필요하다. – globetrotter

2

, 당신은 get_sections() -returned 배열 또는 객체에 동적 사용자 정의 정렬을 할 usort()를 사용하고 기존 코드를 활용할 수 있습니다. (for/foreach 루프에서 같은 작업을 수행하는 것보다 조금 더 우아합니다.)

+0

감사합니다. 감사합니다! – globetrotter