Quick actions

cmd+k|ctrl+k

Navigation

Languages

How to break nest loop (solutions)

Snippet info

Language

Php

Visibility

public

Author

zjmainstay

Created

2016-07-12T01:39:34Z

Updated

2016-07-12T02:23:37Z

<?php

    $investList = [
        [
            'id'    => 1,
            'cash'  => 1000,
        ],
        [
            'id'    => 2,
            'cash'  => 4000,
        ],
        [
            'id'    => 111,
            'cash'  => 10000,
        ],
        [
            'id'    => 3,
            'cash'  => 1000,
        ],
        [
            'id'    => 4,
            'cash'  => 3000,
        ],
        [
            'id'    => 5,
            'cash'  => 2000,
        ],
    ];
    
    $refundList = [
        [
            'invest_id'    => 1,
            'cash'  => 1000,
        ],
        [
            'invest_id'    => 2,
            'cash'  => 4000,
        ],
        [
            'invest_id'    => 3,
            'cash'  => 1000,
        ],
        [
            'invest_id'    => 4,
            'cash'  => 3000,
        ],
        [
            'invest_id'    => 5,
            'cash'  => 2000,
        ],
        [
            'invest_id'    => 111,
            'cash'  => 10000,
        ],
    ];
    
    $investList = array_combine(array_column($investList, 'id'), $investList);
    
    foreach($refundList as $index => $refund) {
        #foreach($investList as $invest) {
            #if($invest['id'] == $refund['invest_id']) {
            if(isset($investList[$refund['invest_id']])) {
                $invest = $investList[$refund['invest_id']];
                $refundList[$index]['invest_cash'] = $invest['cash'];
            }
            #}
        #}
    }
    
    print_r($refundList);
    
    //When the investList run up to 10000, the loop times can be 10000*10000=100000000, how to optimize this?
    
INFO