Search code examples
phparrayscodeignitertransposebatch-updates

Transpose data from multiple flat arrays and add second level associative keys before calling CodeIgniter's update_batch() method


I'm having a problem with restructuring some array data.

I'm working with bulk upload data(Update) to database. So I have 3 arrays like this:

Array ( [0] => aaa [1] => ccc [2] => eee [3] => ggg ) 
Array ( [0] => bbb [1] => ddd [2] => fff [3] => hhh ) 
Array ( [0] => 1662 [1] => 1663 [2] => 1664 [3] => 1665 )

I need to restructure the array to the order below.

$data = array(
   array(
      'title' => 'aaa' ,
      'Info' => 'bbb' ,
      'id' => '1662'
   ),
   array(
      'title' => 'ccc' ,
      'Info' => 'ddd' ,
      'id' => '1663'
   ),
      array(
      'title' => 'eee' ,
      'Info' => 'fff' ,
      'id' => '1664'
   ),
      array(
      'title' => 'ggg' ,
      'Info' => 'hhh' ,
      'id' => '1665'
   )
);

$this->db->update_batch('mytable', $data,'id'); 

How I can restructure the array?

Note : array content will be keep change when various type is selected.

ex:

array(
      'title' => 'Any value' ,
      'Info' => 'Any value' ,
      'id' => 'Any Id'

Solution

  • This may help you

    [akshay@localhost tmp]$ cat test.php 
    <?php
    
    $a1 = array('aaa','ccc','eee','ggg');
    $a2 = array('bbb','ddd','fff','hhh');
    $a3 = array(1662,1663,1664,1665);
    
    // Output
    $output = array_map(function($a,$b,$c){ return array('title'=>$a,'Info'=>$b,'id'=>$c);},$a1,$a2,$a3)
    
    print_r ( $output );
    
    // Here add your update statement
    // $this->db->update_batch('mytable', $output,'id');
    
    ?>
    

    Output

    [akshay@localhost tmp]$ php test.php 
    Array
    (
        [0] => Array
            (
                [title] => aaa
                [Info] => bbb
                [id] => 1662
            )
    
        [1] => Array
            (
                [title] => ccc
                [Info] => ddd
                [id] => 1663
            )
    
        [2] => Array
            (
                [title] => eee
                [Info] => fff
                [id] => 1664
            )
    
        [3] => Array
            (
                [title] => ggg
                [Info] => hhh
                [id] => 1665
            )
    
    )