Home > Software engineering >  Multidimensional Array as Variables to save in dB
Multidimensional Array as Variables to save in dB

Time:02-11

I have a multidimensional array

output_querys =  array(2) { [0]=> array(5) { ["ID"]=> string(1) "2" ["Code"]=> string(6) "AWS001" ["BCode"]=> string(4) "B001" ["Des"]=> string(4) "loan" ["subCat"]=> string(3) "SWA" } [1]=> array(5) { ["ID"]=> string(1) "4" ["Code"]=> string(6) "AWS002" ["BCode"]=> string(4) "B002" ["Des"]=> string(3) "tax" ["subCat"]=> string(3) "PJA" } }

I want to get this to a variable and then save into dB.I have tried all the methods that has mentioned in related problems nothing worked. Errors I got 1.trying non-object 2.Illegal string offset

what I was trying to do is

foreach($output_querys as $output_query){
  $Pv_ID = $output_query->ID;
   $Pv_Code = $output_query->Code;
      $Pv_Description = $output_query->Des;
      
    
    $data_final = array(id => $Pv_ID, code => $Pv_Code, des => $Pv_Description);
                                                
      }
      db->insert(abc, $data_final);

what is the problem here??.even i tried with json encode and still shows the "Illegal string offset"

        $Pv_ID= json_decode($output_query['ID']);
                                       
        $Pv_Code = json_encode($output_query['Code'],true);
                                            
        $Pv_Description = json_encode($output_query['Des'],true);

CodePudding user response:

I tried your given array and code

    <?php
  $output_querys = array( 
    0 => array( 
            "ID" => "2", 
            "Code" => "AWS001", 
            "BCode" => "B001", 
            "Des" => "loan", 
            "subCat" => "SWA" 
    ),    
    1 => array( 
            "ID" => "4", 
            "Code" => "AWS002", 
            "BCode" => "B002", 
            "Des" => "tax", 
            "subCat" => "PJA" 
        )
);
  foreach($output_querys as $output){
    print_r($output['Code']); echo "\n";
    
  }
?>

It is working fine on my end. Here's the working example

I think you need to do this as well, if you want to insert 1 by 1 then move the insert in foreach loop

foreach($output_querys as $output_query){
  $Pv_ID = $output_query->ID;
   $Pv_Code = $output_query->Code;
      $Pv_Description = $output_query->Des;
      
    
    $data_final = array(id => $Pv_ID, code => $Pv_Code, des => $Pv_Description);
     db->insert(abc, $data_final);                                           
      }
      
  • Related