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条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料