array("start" => "0-6ren">
gpt4 book ai didi

php - 合并不同长度的数组

转载 作者:搜寻专家 更新时间:2023-10-31 21:36:19 24 4
gpt4 key购买 nike

给定以下格式的 2 个数组:

$array1 = array("1", "2", "3", "4", "5");

$array2 = array(
0 => array("start" => "09:00", "end" => "17:00"),
1 => array("start" => "18:00", "end" => "20:00")
);

我需要合并以便结果是:

$result = array(
array(
"start_day" => "1",
"start_time" => "09:00",
"end_day" => "1",
"end_time" => "17:00"
),
array(
"start_day" => "1",
"start_time" => "18:00",
"end_day" => "1",
"end_time" => "20:00"
)
// and so on for each item in $array1
);

两个数组的长度可以不同,但​​ $array2 中的每一项都必须应用于 $array1 中的一项。只是把它扔出去看看是否有人对这种合并有任何经验。我当前的解决方案只给我一个长度等于 $array2 长度的结果数组。现在正在处理此问题,但如有任何见解,我们将不胜感激!

最佳答案

像这样:

$result = [];
foreach($array1 as $elem1) {
foreach($array2 as $elem2) {
$result[] = array(
"start_day" => $elem1,
"start_time" => $elem2['start'],
"end_day" => $elem1,
"end_time" => $elem2['end']
);
}
}

关于php - 合并不同长度的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18599893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com