开发者

how do I get array index number in 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?


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>";


foreach($this->cart as $index => $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($index)\">Delete</a></td></tr>"; 
 } 


foreach($this->cart as **$index** => $value) {
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜