-2

我正在尝试将 array_reverse 函数实现到这个 foreach 数组中,我相信我在第 3 行调用了错误的变量(嗯,4)

<?php
    $j=1;
    $skill_slugs = array_reverse( $skill_slugs );

    foreach ($skills as $skill) {               
        $skill = get_term_by( 'slug', trim(htmlentities($skill)), 'skill');
        if($skill) {
            $skill_slug = $skill->slug;             
            $skill_slugs .= $skill_slug . ",";
            $a = '<li><a href="#" data-filter=".'.$skill_slug.'">';
            $a .= $skill->name;                 
            $a .= '</a></li>';
            echo $a;
            echo "\n";
            $j++;
        }         
    }
?>
4

1 回答 1

1

如果您想循环遍历新反转的数组...

foreach ($skills as $skill)

应该

foreach ($skill_slugs as $skill)

更新

// This array is populated within the if-block below
$slugs = array();

// Foreach item in the reversed array, assign a handle of "skill_slug"
foreach ( array_reverse( $skill_slugs ) as $skill_slug ) {

  // Attempt to get Term Data from WordPress
  $s = get_term_by( 'slug', trim(htmlentities($skill_slug)), 'skill' );

  // If Term Data was returned, increment $j and proceed
  if ( $s && $j++ ) {

    // Push Term slug into our $slugs array
    array_push( $slugs, $s->slug );

    // Output a new list-item for this Term
    printf("<li><a href='#' data-filter='%s'>%s</a></li>", $s->slug, $s->name);

  }

}

您为每个变量选择的名称在这里有很多令人困惑的歧义。我想在这里稍微解释一下。此外,您不需要这么多echo语句,因此我将其简化为单个格式化字符串。最后,我将你的 slug 推到一个数组上,而不是将它们连接到一个字符串上。如果您想用逗号将它们列出来,请使用join()

$slugs = array( "PHP", "JavaScript", "C#" );

// PHP, JavaScript, C#
echo join( ", ", $slugs );
于 2012-05-27T22:24:07.773 回答