匹配2个多维数组值

时间:2015-05-25 10:44:04

标签: php arrays multidimensional-array

我在codeignitor工作。我有两个不同的数组。

我的代码是:

bind

第一个数组是这样的:

<?php $i = 1;
    if(!empty($result)) {
        foreach($result as $res) {

            foreach($result1 as $res1) {

            if($res->bid == $res1->branch_id){

            ?>
            <tr>
                <td><?php echo $i; ?></td>
                <td><?php echo date('d-m-Y'); ?></td>
                <td><?php echo $res->bid.'('.$res->bid.')'; ?></td>
                <td><?php $main = $res->dp - $res1->cp; echo $main;?></td>
                <td><a href="/bhumisoft/admin/debit_payment?bid=<?php echo $res->bid; ?>">Debit</a></td>
            </tr>
               <?php 

                 }else{?>
                <tr>
                <td><?php echo $i; ?></td>
                <td><?php echo date('d-m-Y'); ?></td>
                <td><?php echo $res->bid.'('.$res->bid.')'; ?></td>
                <td><?php echo $res->dp; ?></td>
                <td><a href="/bhumisoft/admin/debit_payment?bid=<?php echo $res->bid; ?>">Debit</a></td>
            </tr>
         <?php                       } ?>

            <?php
            $i++;
        }
    }}
    else {
        ?><tr><td colspan="13">No Records Found..!!</td></tr><?php
    }
    ?>

另一个阵列是这样的:

Array
(
[0] = stdClass Object
    (
        [dp] = 1000
        [bid] = 0
    )

[1] = stdClass Object
    (
        [dp] = 16500
        [bid] = 10
    )

[2] = stdClass Object
    (
        [dp] = 31000
        [bid] = 102
    )

[3] = stdClass Object
    (
        [dp] = 115000
        [bid] = 11
    )

[4] = stdClass Object
    (
        [dp] = 50000
        [bid] = 111
    )

[5] = stdClass Object
    (
        [dp] = 1000
        [bid] = 115
    )

[6] = stdClass Object
    (
        [dp] = 5000
        [bid] = 116
    )

 )

现在,我希望将数组与bid和branch_id匹配。如果两者相同,则从dp中减去cp.Otherwise使用bid打印dp。那么我应该编写什么代码?

1 个答案:

答案 0 :(得分:0)

$array1 = your first array;
$array2 = your second array;


foreach ($array1 as &$record) {
    foreach ($array2 as &$record2) {
         if ($record['bid'] == $record2['branch_id']) {
              $record['dp'] = $record['dp'] - $record2['cp'];
         } else {
             echo $record['dp'] . " Bid: ". $record['bid'];
         }
    }

}