2011-11-16 98 views
1

我需要获取数组元素的索引,在我的例子中$ch是一个数组元素,我需要索引值(例如:overview=array[0],$arval = 0),所以我可以打印$tabs[$arval+1]如何获得数组元素的索引

<?php 
$tab ='overview,gallery,video,songs$value1$value2$value3$value4'; 
$tabs = explode('$',$tab); 
$tabname = explode(',',$tabs[0]); 
echo '<div id="tab" style="float:left;width:100%;height:30px;background:#333">'; 
foreach($tabname as $i) 
{ 
echo '<a id="'.$i.'" style="color:#fff;padding:2px 10px;" href="?tab='.$i.'" >'.$i.'</a>'; 
} 
echo '</div>'; 


if(isset($_GET['tab'])) 
    { 
     $ch=$_GET['tab']; 
      foreach($tabname as $i){ 
       if ($ch == $i) 

      // get the array index of the current element $arval 
      // echo $tabs[$arval+1] 

     } }  ?> 

我该如何实现它?

回答

4
foreach($tabname as $index => $i){ 
        ^^^^^^^^^ 
1

在你foreach你需要这样做:

foreach($tabname as $index => $value){ 
// $index is the index 
// $value is the value 

    if ($ch == $i) 

     // get the array index of the current element $arval 
     // echo $tabs[$arval+1] 

} 
+0

感谢队友,IAM坚果 – Ezhil

1

也许这会为你工作:

if(isset($_GET['tab'])) 
{ 
     $ch=$_GET['tab']; 
     if($key = array_search($ch, $tabname, true)) 
      // get the array index of the current element $arval 
      echo $tabs[$key]; 

     } 
}