Abdulla Nilam
Abdulla Nilam

Reputation: 38609

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'

Upvotes: 0

Views: 105

Answers (2)

mickmackusa
mickmackusa

Reputation: 47904

Making iterated calls of get_defined_vars() offers succinct elegance. Just name the column parameters as you wish associative second level keys to be.

Code: (Demo)

$a1 = ['aaa', 'ccc', 'eee', 'ggg'];
$a2 = ['bbb', 'ddd', 'fff', 'hhh'];
$a3 = [1662, 1663, 1664, 1665];

var_export(
    array_map(fn($title, $Info, $id) => get_defined_vars(), $a1, $a2, $a3)
);

Related:

Beyond those, if you want to build the desired associative keys into the assembly of a merged input array, you'll be able to cleanly write a nested loop process which can be found at: Transposing multidimensional arrays in PHP

Upvotes: 0

Akshay Hegde
Akshay Hegde

Reputation: 16997

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
        )

)

Upvotes: 2

Related Questions