dongxiang5879 2010-09-24 17:03
浏览 82
已采纳

如何在PHP中获取数组索引号?

I'm sure this is a stupid question, but it's Friday and my brain just can't figure it out. I have an array of arrays, like so:

$cart = Array ( 
[0] => Array ( [TypeFlag] => S [qty] => 2 [denom] => 50  [totalPrice] =>  100 )
[1] => Array ( [TypeFlag] => V [qty] => 1 [denom] => 25  [totalPrice] => 25 ) 
) 

I'm looping through this array and printing out table rows, one for each internal array. This part works fine. I now need to include a link in one table cell that contains the actual index number of the internal array, so that I can run specific functions on that array. I know how to access a specific array element, like $cart[0], but how can I get the actual zero when I'm writing my links? The loop to write the table currently looks like this:

 foreach($this->cart as $value) {
    $finalTotal += $value['totalPrice'];
         echo "<tr>";
         foreach($value as $key=>$item) {   
        //create a new row for each internal array element  
                echo "<td>".$item."&nbsp;</td>";
          }
      //now add a link for each external array element
          echo "<td><a href=\"myFunction(arrayIndex)\">Delete</a></td></tr>";
 }

What I need to do is replace the arrayIndex param in the myFunction with the actual index number of the currently-looping array, so that, given the example array, I'd end up with table code that looked like this:

<tr>
    <td>S</td>
    <td>2</td>
    <td>50</td>
    <td>100</td>
    <td><a href="myFunction(0)">Delete</a></td>
</tr>
<tr>
    <td>V</td>
    <td>1</td>
    <td>25</td>
    <td>25</td>
    <td><a href="myFunction(1)">Delete</a></td>
</tr>

Can anyone please give my poor brain a jumpstart?

  • 写回答

3条回答 默认 最新

  • dsf12123 2010-09-24 17:06
    关注

    Just change

    foreach($this->cart as $value) 
    

    to

    foreach($this->cart as $cart_key => $value) 
    

    and then use it in your echo as:

    echo "<td><a href=\"myFunction($cart_key)\">Delete</a></td></tr>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?