向现有数组添加新的键值

时间:2018-10-15 09:01:48

标签: php arrays

我有两个数组。我想将第二个数组的值添加到第一个数组作为键值。这是我拥有的数组

//主阵列

Array
(
    [0] => Array
        (
            [commodity] => Abacavir (ABC) 300mg Tabs
            [allocated] => 
            [balance] => 1388
            [mos] => 3
            [year] => 2018
            [month] => May
            [drug_id] => 1
            [data_date] => 2018-05-01
        )

    [1] => Array
        (
            [commodity] => Abacavir/Lamivudine (ABC/3TC) 120/60mg FDC Tabs
            [allocated] => 
            [balance] => 1185
            [mos] => 26
            [year] => 2018
            [month] => May
            [drug_id] => 4
            [data_date] => 2018-05-01
        )
)

// MOS阵列

Array
(
    [0] => 3
    [1] => 4
)

//需要的结果

Array
(
    [0] => Array
        (
            [commodity] => Abacavir (ABC) 300mg Tabs
            [allocated] => 
            [balance] => 1388
            [mos] => 3
            [year] => 2018
            [month] => May
            [drug_id] => 1
            [data_date] => 2018-05-01
            [amc] => 3
        )

    [1] => Array
        (
            [commodity] => Abacavir/Lamivudine (ABC/3TC) 120/60mg FDC Tabs
            [allocated] => 
            [balance] => 1185
            [mos] => 26
            [year] => 2018
            [month] => May
            [drug_id] => 4
            [data_date] => 2018-05-01
            [amc] => 4
        )
)

到目前为止我已经尝试过的

foreach ($sub_res as $key => $res) {            
    $query2 = $this->db->query("SELECT  $amcfunction($drug_id,$no_of_mos,'$date'$amc) amc")->result_array();
    $sub_res[$key]['amc'] = $query2[0]['amc'];

}

这样,它仅将amc附加到最后一个数组。有什么建议么? $ sub_res是我将amc添加到的第一个数组的结果

3 个答案:

答案 0 :(得分:0)

为什么不仅仅遍历数组?

foreach ($main as &$item) {
    $item['amc'] = array_shift($mos);
}
unset($item);

array_shift只会从$mos数组中删除第一项,并添加到$main的每次迭代中。
请注意,我使用了&符号&-创建了引用,其结果是,我也取消了该项目的设置,以便没有悬挂的引用。

答案 1 :(得分:0)

为此foreach很快。

这是一个示例的简化版本:

// simplified main array
$main[] = array('commodity' => 'Abacavir (ABC) 300mg Tabs');
$main[] = array('commodity' => 'Abacavir/Lamivudine (ABC/3TC) 120/60mg FDC Tabs');

// MOS Array
$mos = array(3,4);

foreach($mos as $k => $v) {
    $main[$k]['amc'] = $v;
}
echo '<pre>';
var_dump($main);
echo '</pre>';
exit;

结果:

array(2) {
    [0]=>  array(2) {
        ["commodity"]=> string(25) "Abacavir (ABC) 300mg Tabs"
        ["amc"]=> int(3)
    }
    [1]=>  array(2) {
        ["commodity"]=> string(47) "Abacavir/Lamivudine (ABC/3TC) 120/60mg FDC Tabs"
        ["amc"]=> int(4)
    }
}

答案 2 :(得分:0)

尝试以下代码:

foreach ($sub_res as $key => $res) {            
   $query2 = $this->db->query("SELECT  $amcfunction($drug_id,$no_of_mos,'$date'$amc) amc")->result_array();
   $sub_res[$key] = array_merge($res, ['amc' => $query2[0]]);

}