skip to Main Content

I have this array to save to database:

{"i_barcode_id":["3","3"],"i_barcode_sn":["8999999565404","6933412700043"]}

how do I save it to DB so the databse should be like this.

i_barcode_id     i_barcode_sn
3                8999999565404
3                6933412700043

this is my current script.

foreach($myarray as $row){          
        
        $dataadd_sto_d  = array (                           
            'ID' => $rows['i_barcode_id'],
            'SN' => $rows['i_barcode_sn']
        );
        
        $insertsto_d    = $this->MWarehouse->add_sto_d($dataadd_sto_d); //insert script
        
};

The script failed to save to database. I do not know why. any

2

Answers


  1. Use this tested working

    $key = array();
    $value = array();
    foreach($myarray as $row){                                  
       $id => $rows['i_barcode_id'],
       $sn => $rows['i_barcode_sn']
        array_push($key, $id);
        array_push($value, $sn);
    }
    $insert_data = array_combine($key, $value);  
    return $this->MWarehouse->add_sto_d($insert_data);
    

    Note
    array_combine() will now throw a ValueError if the numberof elements for each array is not equal; previously this function returned false instead.

    Login or Signup to reply.
  2. You have some typos in your Code like foreach(... as $row) and later you want to access $rows

    My Attemp would be, to grap i_barcode_id or i_barcode_sn to loop and take the value index to get the data from the other array.
    Example:

    //true at the end, cause i have something against stdClass without any reason
    $myarray = json_decode('{"i_barcode_id":["3","3"],"i_barcode_sn":["8999999565404","6933412700043"]}',true);
    
    foreach($myarray['i_barcode_id'] as $key => $val){
        $insertArray=array(
            "ID" => $val,
            "SN"=>$myarray['i_barcode_sn'][$key]
        );
        //Your Insert Script
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search