将2个非相等数组组合成多维数组

时间:2019-07-15 15:35:16

标签: php arrays

我有2个数组:

第一[]:

Array
(
[First / Building] => code 100
[Second - Closed and Covered Cans] => code 200
)

second []:

Array
(
[0] => 1,000.00
[1] => 2,000.00
[2] => 3,000.00
)

我想要的东西是这样的:

final []

Array
(
    [First / Building] => code 100
        (
            [0] => 1,000.00
        )

    [Second - Closed and Covered Cans] => code 200
        (
            [0] => 2,000.00
        )

)

(在这种情况下,[2] => 3,000.00不匹配)

如果first []的计数大于> second [],则说:

第一[]

Array
(
[First / Building] => code 100
[Second - Closed and Covered Cans] => code 200
[Third - Closed and Covered Cans] => code 300
[Forth - Closed and Covered Cans] => code 400
)

second []

Array
(
[0] => 1,000.00
[1] => 2,000.00
[2] => 3,000.00
)

我想要的输出:

final []

Array
(
    [First / Building] => code 100
        (
            [0] => 1,000.00
        )

    [Second - Closed and Covered Cans] => code 200
        (
            [0] => 2,000.00
        )
     [Third - Closed and Covered Cans] => code 300
        (
            [0] => 3,000.00
        )
     [Forth - Closed and Covered Cans] => code 400
        (
        ) 
)

(在这种情况下,不留任何值)

始终将第一个数组中的值与第二个数组中的值配对。我尝试使用array_combine(),但这是不可行的,因为它们的计数不同。

1 个答案:

答案 0 :(得分:0)

array_combine没什么用,因为您没有键数组。您的first数组已经是一个关联数组,并且您希望结果具有相同的键。

使用foreach循环遍历第一个数组,同时增加变量以获取第二个数组中的索引。

$final = [];
$i = 0;
foreach ($first as $key => $code) {
    $final[$key] = ["code" => $code, "price" => $second[$i]];
    $i++;
}