。我有两个数组
第一个
Array
(
[0] => Array
(
[date] => 2012-01-10
[result] => 65
[name] => Les océans
)
[1] => Array
(
[date] => 2012-01-11
[result] => 75
[name] => Les mers
)
[2] => Array
(
[date] => 2012-01-13
[result] => 66
[name] => Les continents
[type] => Scores
)
)
第二个
Array
(
[0] => Array
(
[date_end] => 2012-01-12
[result] => 60
[name] => Step#1
[type] => Summary
)
)
我想要这个作为我的最终结果
Array
(
[0] => Array
(
[date] => 2012-01-10
[result] => 65
[name] => Les océans
)
[1] => Array
(
[date] => 2012-01-11
[result] => 75
[name] => Les mers
)
[2] => Array
(
[date_end] => 2012-01-12
[result] => 60
[name] => Step#1
[type] => Summary
)
[3] => Array
(
[date] => 2012-01-13
[result] => 66
[name] => Les continents
[type] => Scores
)
)
所以....我需要将我的第一个数组与第二个数组合并,并且我想按日期订购这个新数组!...有人可以帮助我提示我这样做吗?谢谢!
array_merge 和 usort 是你的朋友。
function cmp($a, $b){
$ad = strtotime($a['date']);
$bd = strtotime($b['date']);
return ($ad-$bd);
}
$arr = array_merge($array1, $array2);
usort($arr, 'cmp');
使用array_merge()将数组合并,然后使用sort对sort()进行排序,非常简单。你想要一个例子吗?
这应该为你排序:
function dateSort($a,$b){
$dateA = strtotime($a['date']);
$dateB = strtotime($b['date']);
return ($dateA-$dateB);
}
$arrayOne = array(
array(
'date' => '2012-01-10',
'result ' => 65,
'name' => 'Les océans'
),
array(
'date' => '2012-01-11',
'result ' => 75,
'name' => 'Les mers'
),
array(
'date' => '2012-01-13',
'result ' => 66,
'name' => 'Les continents',
'type' => 'Scores'
)
);
$arrayTwo = array(
array(
'date' => '2012-01-12',
'result ' => 60,
'name' => 'Step#1',
'type' => 'Summary'
)
);
// Merge the arrays
$combinedArray = array_merge($arrayOne,$arrayTwo);
// Sort the array using the call back function
usort($combinedArray, 'dateSort');
array_merge
您的数组,然后使用以下代码作为如何对其进行排序的示例。
function sortDate($val1, $val2)
{
if ($val1['date'] == $val2['date']) {
return 0;
}
return (strtotime($val1['date']) < strtotime($val2['date'])) ? -1 : 1;
}
$array = array(
array('date' => '2012-01-10'),
array('date' => '2011-01-10'),
array('date' => '2012-01-01')
);
usort($array, "sortDate");
print_r($array);
strtotime()
或任何其他日期解析器进行解析)。代码:(演示)
$result = array_merge($array1, $array2);
usort(
$result,
fn($a, $b) => ($a['date'] ?? $a['date_end']) <=> ($b['date'] ?? $b['date_end'])
);
var_export($result);
输出:
array (
0 =>
array (
'date' => '2012-01-10',
'result' => 65,
'name' => 'Les océans',
),
1 =>
array (
'date' => '2012-01-11',
'result' => 75,
'name' => 'Les mers',
),
2 =>
array (
'date_end' => '2012-01-12',
'result' => 60,
'name' => 'Step#1',
'type' => 'Summary',
),
3 =>
array (
'date' => '2012-01-13',
'result' => 66,
'name' => 'Les continents',
'type' => 'Scores',
),
)