gpt4 book ai didi

php - 排序和合并关联数组 (PHP)

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

我有 2 个关联数组:

[0] => Array (
[time] => 09:00:00
[name] => To do something 1
)
[1] => Array (
[time] => 09:30:00
[name] => To do something 2
)
[2] => Array (
[time] => 10:00:00
[name] => To do something 3
)

[0] => Array (
[time] => 09:00:00
)
[1] => Array (
[time] => 09:15:00
)
[2] => Array (
[time] => 09:30:00
)
[3] => Array (
[time] => 09:45:00
)
[4] => Array (
[time] => 10:00:00
)

需要再做一个关联数组:

  • 如果第二个数组中的字段 [time] 等于第一个数组中的字段 [time],则添加 [name];
  • 如果第二个数组中的字段 [time] 不等于第一个数组中的字段 [time],则添加空 [name]。

应该是这样的:

[0] => Array (
[time] => 09:00:00
[name] => To do something 1
)
[1] => Array (
[time] => 09:15:00
[name] =>
)
[2] => Array (
[time] => 09:30:00
[name] => To do something 2
)
[3] => Array (
[time] => 09:45:00
[name] =>
)
[4] => Array (
[time] => 10:00:00
[name] => To do something 3
)

最佳答案

经过一番摸索,我让它对你有用。

这是您可以使用的代码:

$array3 = array();

foreach ($array2 as $key2 => $value2){
$found = false;

foreach ($array1 as $key1 => $value1){
if ($array1[$key2]['time'] == $array2[$key2]['time']) {
$array3[$key2]['time'] = $array1[$key1]['time'];
$array3[$key2]['name'] = $array1[$key1]['name'];
$found = true;
}
}
if (!$found){
//add
$array3[$key2]['time'] = $array2[$key2]['time'];
$array3[$key2]['name'] = "";

}
}

print_r($array3);

关于php - 排序和合并关联数组 (PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32734042/

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