phparrayscodeignitermultidimensional-arraysubmission

Merge and transpose 2d submission data and append a single value to each row


I need to add a solitary element to each level of a 2d array which was formed by restructuring the columns of two associative elements as indexed rows.

Here is the transposed array:

Array (
    [0] => Array ( 
        [actor_rt_id] => 162683283,
        [item_number] => 3
    ) 
    [1] => Array ( 
        [actor_rt_id] => 162657351,
        [item_number] => 5
    ) 
)

This code produces the array. The commented out line is what I tried to add to the array. The code before the comment creates the array.

$data_itemone['actor_rt_id'] = $this->input->post('actor_id');
$data_itemtwo['item_number'] = $this->input->post('item_number');
$data_item = array_merge($data_itemone, $data_itemtwo);
$res = [];
foreach ($data_item as $key => $value) {
    foreach ($value as $data => $thevalue) {
        $res[$data][$key] = $thevalue;
        //$res['film_id'] = $film_id;
    }
}

I have an another variable I need to add from post which is a single string.

$film_id = $this->input->post('film_id');

I need it to be in the array like so -

Array (
    [0] => Array ( 
        [actor_rt_id] => 162683283,
        [item_number] => 3,
        [film_id]    => 52352
    ) 
    [1] => Array ( 
        [actor_rt_id] => 162657351,
        [item_number] => 5,
        [film_id]    => 52352
    ) 
)

...but my code (uncommented) produces -

Array (
    [0] => Array ( 
        [actor_rt_id] => 162683283,
        [item_number] => 3 
    )
    [film_id] => 16639,
    [1] => Array (
        [actor_rt_id] => 162657351,
        [item_number] => 5
    )
)

Solution

  • Change

    $res['film_id'] = $film_id;

    to

    $res[$data]['film_id'] = $film_id;

    this will add it to the right array.