简体   繁体   中英

Adding same element to every level of array php

I need to add another another element to each level of the array (sorry, think that is bad terminology).

I have an 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 )
 )

Tried a few things. Can't seem to get it to work.

Change

$res['film_id'] = $film_id;

to

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

this will add it to the right array.

How if you try this.

$data_itemone['actor_rt_id'] = [123, 245];
$data_itemtwo['item_number'] = [456, 789];
$film_id = 52352;
$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[$data]['film_id'] = $film_id;
    }
}
print_r($res);

Try this one

<?
    $data_itemone['actor_rt_id'] = $this->input->post('actor_id');
    $data_itemtwo['item_number'] = $this->input->post('item_number');
    $film_id = $this->input->post('film_id');
    $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[$data]['film_id'] = $film_id;
        }
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM