phpmultidimensional-arrayforeach

Use value from first array as a variable in the second array


I am dealing with two rows of a table, each with nested foreach loops based on separate arrays. I want to be able to make a value from the first row, available to the second row. Looking at the data below, I want to be able to have access to the values of 3, 1, and 2, and use those values (to determine column widths) in the second array of data.

This is the first data array, used in row 1:

Array
(
[Nov 18, 2011] => Array
    (
        [C] => 3
        [I] => 1
    )
[Nov 22, 2011] => Array
    (
        [C] => 2
    )
)

This is the second data array, used in row 2:

Array
(
[Nov 18, 2011] => Array
    (
        [C] => 107705.5792
        [I] => 44561.52
    )
[Nov 22, 2011] => Array
    (
        [C] => -8992.8352
    )
)

Here is the current table structure for the two rows:

<tr> <!-- ROW 1 -->
<th>f1</th>
<td>f1</td>
<?php foreach($array1 as $a1) { ?>
     <?php foreach ($a1 as $k=>$v) { ?>        
        <td colspan=<?php echo $v ?>>
            <?php echo ($k."_".$v) ?>
        </td>
     <?php } ?>           
<?php } ?>
</tr>
<tr> <!-- ROW 2 -->
<th>f2</th>
<td>f2</td>
<?php foreach($array2 as $a1) { ?>
     <?php foreach ($a1 as $k=>$v) { ?>        
        <td>
            <?php echo ($k."_".$v) ?>
        </td>
     <?php } ?>           
<?php } ?>
</tr>

I think that what needs to happen is that the two arrays need to be combined in some way. I need this structure for my data:

[C] => 107705.5792 - needs to have column width of 3 
[I] => 44561.52 - needs to have column width of 1  
[C] => -8992.8352 - needs to have column width of 2

I hope I have explained this clearly enough. Thanks for any help you can offer.


Solution

  • You can combine each entry from the first array together with the entry from the second array as an array with two values:

    $combined = $first;
    foreach($combined as $date => $vs)
    {
        foreach($vs as $k => &$v)
        {
           $v = array($v, $second[$date][$k]);
        }
    }
    unset($v);
    

    Then you can access both values like this:

    list($a, $b) = $combined['Nov 22, 2011']['C'];
    // $a: 2
    // $b: -8992.8352
    

    Usage:

    ...
    <tr> <!-- ROW 2 -->
    <th>f2</th>
    <td>f2</td>
    <?php foreach($combined as $dates) { ?>
         <?php foreach ($dates as $date=>$v)
               {
                   list($colspan, $value) = $v;
         ?>
            <td colspan=<?php echo $colspan; ?>>
                <?php echo ($date."_".$value) ?>
            </td>
         <?php } ?>           
    <?php } ?>
    </tr>