Php foreach排序有三个变量

时间:2015-07-04 13:10:47

标签: php foreach

我正在尝试使用foreach循环来打印出在数组$term->description中的三个变量之一之后排序的链接。 $term->name的值是link元素中的文本。如何在同一个foreach循环中使用第三个变量$term->slug为链接添加href属性?我试图制作两个单独的数组并使用array_combine,但无济于事。

以下是适用于两个变量的代码。为了清楚起见,我简单地在其所需位置添加了$term->slug

$terms = wp_get_object_terms( $post->ID, $taxonomy );
$a = array();
foreach ($terms as $term ) : 
    $a[] = array( $term->name, $term->description, $term->slug);
endforeach; 


// print_r($a); 
// Array ( [0] => Array ( [0] => Los Angeles [1] => City [2] => los-angeles ) [1] => Array ( [0] => San Francisco [1] => City [2] => san-francisco ) [2] => Array ( [0] => San Diego [1] => City [2] => san-diego ) [3] => Array ( [0] => United States [1] => Country [2] => united-states ) ) 

foreach ($a as $key => $value) {
    $return[$value[1]][] = $value[0];
}   

foreach ($return as $key => $value) {
    echo $key.": <span class='tags'><a href='$term->slug'>".implode('</a></span>,<span class="tags"><a href="$term->slug">', $value)."</a></span>";
}

// Outputs:
// City: Los Angeles  San Fransisco  San Diego
// Country: United States

1 个答案:

答案 0 :(得分:1)

代码:

<?php
  error_reporting('E_ALL');

  $a = Array(Array("Los Angeles","City","los-angeles"),Array("San Francisco","City","san-francisco"),Array("San Diego","City","san-diego"),Array("United States","Country","united-states"));

  foreach ($a as $key => $value) {
      $return[$value[1]][] = array("name"=>$value[0],"slug"=>$value[2]);
  }   


  foreach ($return as $key => $value) {
    echo $key.":";
      foreach($value as $newvalue){
       echo '<span class="tags"><a href="'.$newvalue["slug"].'">'.$newvalue["name"].'</a>&nbsp;</span>';
    }
    echo "<br>";
  }

<强>输出:

City:<span class="tags"></span><a href="los-angeles">Los Angeles</a>&nbsp;<span class="tags"></span><a href="san-francisco">San Francisco</a>&nbsp;<span class="tags"></span><a href="san-diego">San Diego</a>&nbsp;<br>Country:<span class="tags"></span><a href="united-states">United States</a>&nbsp;<br>