0
foreach ( $this->parent->get_sections(null, $this->parent->author) as $section)
{
  //...
}

我想做的是强制循环$section按我想要的顺序输出每个。每个$section人的名字都可以通过$section->name. 假设我想先输出$section“Section 2”,然后输出“Section 1”(而不是按 的顺序foreach)。我怎么能强迫它这样做?我认为正确的方法是一个for循环,每次都检查部分名称。

4

4 回答 4

4

The proper way would be sorting the results when you call parent->get_sections(). How you would do this is entirely up to the implementation of that class and method. Changing this foreach to for for the sake of sorting seems like a code smell to me.


For the sake of answering the question as technical as possible.

$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]
}
于 2012-09-22T01:58:40.713 回答
2

Especially if you are not aware of the specific number of sections, you could use usort() to do a dynamic custom sort on the get_sections()-returned array or object and then utilize the existing code. (This is a little more elegant, imo, than doing the same in a for/foreach loop).

于 2012-09-22T02:00:07.927 回答
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

if you want it sorted, in say descending order, you can sort it that way and then use a for loop to display.

于 2012-09-22T01:58:32.117 回答
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
}
于 2012-09-22T02:20:51.640 回答