简体   繁体   English

将相同元素添加到数组php的每个级别

[英]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;
        }
    }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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