3

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 Answers 3

2

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>";
Sign up to request clarification or add additional context in comments.

1 Comment

Everyone's answers were pretty much the same (all correct), so I'm just accepting the one that was posted first.
2
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>"; 
 } 

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.