如何在php中的另一个数组的每个索引中插入数组值?

时间:2015-08-21 12:40:55

标签: php arrays codeigniter

我有两个数组,因为我需要在php中插入最后一个键的每个索引和另一个数组键的值。我的样本数组如下。我正在使用codeigniter框架。

第一个阵列:

Array
(
    [0] => stdClass Object
        (
            [customer_name] => Cash
            [ordernumber] => 6452424
            [product_name] => Bacardi Rum
            [quantity] => 1
            [unit_price] => 25.00
            [inv_discount] => 0.00
            [salesman_id] => 25,27
        )

    [1] => stdClass Object
        (
            [customer_name] => Cash
            [ordernumber] => 6452424
            [product_name] => Baileys
            [quantity] => 1
            [unit_price] => 15.00
            [inv_discount] => 0.00
            [salesman_id] => 28,29
        )

)

第二阵列:

Array
(
    [0] => 140140,150150
    [1] => 151151,05180518
)

我需要o / p:

Array
    (
        [0] => stdClass Object
            (
                [customer_name] => Cash
                [ordernumber] => 6452424
                [product_name] => Bacardi Rum
                [quantity] => 1
                [unit_price] => 25.00
                [inv_discount] => 0.00
                [salesman_id] => 25,27
                [salesman] => 140140,150150
            )

        [1] => stdClass Object
            (
                [customer_name] => Cash
                [ordernumber] => 6452424
                [product_name] => Baileys
                [quantity] => 1
                [unit_price] => 15.00
                [inv_discount] => 0.00
                [salesman_id] => 28,29
                [salesman] => 151151,05180518
            )

    )

任何人都可以帮助我,给出一些解决这个问题的想法。

3 个答案:

答案 0 :(得分:3)

在这种情况下,您有一个对象数组( stdClass类型)和另一个数组。回答你的问题,你只需要执行如下所示的代码。

foreach ($secondArray as $key => $value) {
    $firstArray[$key]->salesman = $value;
}

foreach ($firstArray as $key => $object) {
    $object->salesman = $firstArray[$key];
}

答案 1 :(得分:0)

foreach($arrA as $key=>$val){
   $arrA[$key]['salesman'] = $arrB[$key];
}

答案 2 :(得分:0)

只要两个数组的大小相同,array_map就适合:

$resultArray = array_map(function ($rowA, $rowB) {
    $rowA->salesman = $rowB;
    return $rowA;
}, $firstArray, $secondArray);