Skip to content
Advertisement

I’m trying to merge multiple arrays from mysql using for loop. But it’s not working

This is the arrays in MySQL.

This is the arrays in MYSQL.

Here is my PHP code for merging the array. Basically I want to validate whether the user entered number exists.

public function check_serial_from_exist(){
    $serial      = $this->input->post('serial_no_from');
    $scope_id    = $this->input->post('scope_id');       
    $client_id   = $this->input->post('client_id');       

    $get_serials = $this->db->select('used_serials')->where('certification_scope',$scope_id,'clientid',$client_id)->get('tbllabels')->result_array();
    $all_used_serials  = array();
    $status      = 'true';
    
    for($i=0;$i<count($get_serials);$i++){
        $all_used_serials[] = json_decode($get_serials[$i]['used_serials']);                
    }
    
    for($j=0;$j<count($all_used_serials);$j++){
       if(in_array($serial,$all_used_serials[$j])){
           $status = 'false';
       }
       else{
           $status = 'true';
       }
    }
    
    echo ''.$status;
}

When I print the array I got this:

Array ( [0] => Array ( [0] => 10 [1] => 11 [2] => 12 [3] => 13 [4] => 14 [5] => 15 [6] => 16 [7] => 17 [8] => 18 ) [1] => Array ( [0] => 20 [1] => 21 [2] => 22 [3] => 23 [4] => 24 [5] => 25 [6] => 26 [7] => 27 [8] => 28 [9] => 29 [10] => 30 ) [2] => Array ( [0] => 50 [1] => 51 [2] => 52 [3] => 53 [4] => 54 [5] => 55 [6] => 56 [7] => 57 [8] => 58 [9] => 59 [10] => 60 ) [3] => Array ( [0] => 70 [1] => 71 [2] => 72 [3] => 73 [4] => 74 [5] => 75 [6] => 76 [7] => 77 [8] => 78 [9] => 79 [10] => 80 ) [4] => Array ( [0] => 85 [1] => 86 [2] => 87 [3] => 88 [4] => 89 [5] => 90 ) )

Anyone help me to fix this? Thanks in advance.

Advertisement

Answer

In your second for loop you are overwriting the value of $status in each iteration, so ultimately it is set to the result of the final iteration. Using array_merge and doing away with your second loop will resolve this.

public function check_serial_from_exist() {
    $serial      = $this->input->post('serial_no_from');
    $scope_id    = $this->input->post('scope_id');       
    $client_id   = $this->input->post('client_id');       

    $get_serials = $this->db->select('used_serials')->where('certification_scope',$scope_id,'clientid',$client_id)->get('tbllabels')->result_array();
    $all_used_serials  = array();
    
    foreach($get_serials as $row) {
        $all_used_serials = array_merge(
            $all_used_serials,
            json_decode($row['used_serials'])
        );              
    }

    return in_array($serial, $all_used_serials)
}

Storing serialised data in your database is rarely the right solution and you should consider normalising this data.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement