比较数组数组中的一个 ID,只取一行,其中日期按 PHP 中的降序排列
compare an ID in array of arrays and take only a single row with the date in desc order in PHP
我有一个这样的数组:
$data = array (
0 =>
array (
'UserID' => '1',
'ShipPinCode' => '411008',
'createdDate' => '2011-10-04 01:16:54.723',
'Amount' => '1000.00',
),
1 =>
array (
'UserID' => '1',
'ShipPinCode' => '411008',
'createdDate' => '2011-10-04 01:24:24.243',
'Amount' => '1000.00',
),
2 =>
array (
'UserID' => '102818',
'ShipPinCode' => '500072',
'createdDate' => '2011-11-29 12:17:43.880',
'Amount' => '2000.00',
),
3 =>
array (
'UserID' => '100001',
'ShipPinCode' => '500072',
'createdDate' => '2011-11-26 11:49:17.760',
'Amount' => '2000.00',
),
);
我想对它进行排序,对于 UserID 的重复条目,最终输出应该只包含该 UserID 的一行,其中 createdDate 是最大的,即按降序排列。
期望的输出:
array (
0 =>
array (
'UserID' => '1',
'ShipPinCode' => '411008',
'createdDate' => '2011-10-04 01:24:24.243', //only took one row of UserID 1 where the createdDate is the largest.
'Amount' => '1000.00',
),
1 =>
array (
'UserID' => '102818',
'ShipPinCode' => '500072',
'createdDate' => '2011-11-29 12:17:43.880',
'Amount' => '2000.00',
),
2 =>
array (
'UserID' => '100001',
'ShipPinCode' => '500072',
'createdDate' => '2011-11-26 11:49:17.760',
'Amount' => '2000.00',
),
);
在这种情况下,我不知道如何进行比较。
我该怎么做?
您可以按 createdDate
升序排序:
array_multisort(array_column($data, 'createdDate'), SORT_ASC, $data);
然后你可以在 UserID
上提取和索引,这只会保留最后一个:
$result = array_column($data, null, 'UserID');
如果你想重建索引(不需要):
$result = array_values($result);
我有一个这样的数组:
$data = array (
0 =>
array (
'UserID' => '1',
'ShipPinCode' => '411008',
'createdDate' => '2011-10-04 01:16:54.723',
'Amount' => '1000.00',
),
1 =>
array (
'UserID' => '1',
'ShipPinCode' => '411008',
'createdDate' => '2011-10-04 01:24:24.243',
'Amount' => '1000.00',
),
2 =>
array (
'UserID' => '102818',
'ShipPinCode' => '500072',
'createdDate' => '2011-11-29 12:17:43.880',
'Amount' => '2000.00',
),
3 =>
array (
'UserID' => '100001',
'ShipPinCode' => '500072',
'createdDate' => '2011-11-26 11:49:17.760',
'Amount' => '2000.00',
),
);
我想对它进行排序,对于 UserID 的重复条目,最终输出应该只包含该 UserID 的一行,其中 createdDate 是最大的,即按降序排列。
期望的输出:
array (
0 =>
array (
'UserID' => '1',
'ShipPinCode' => '411008',
'createdDate' => '2011-10-04 01:24:24.243', //only took one row of UserID 1 where the createdDate is the largest.
'Amount' => '1000.00',
),
1 =>
array (
'UserID' => '102818',
'ShipPinCode' => '500072',
'createdDate' => '2011-11-29 12:17:43.880',
'Amount' => '2000.00',
),
2 =>
array (
'UserID' => '100001',
'ShipPinCode' => '500072',
'createdDate' => '2011-11-26 11:49:17.760',
'Amount' => '2000.00',
),
);
在这种情况下,我不知道如何进行比较。 我该怎么做?
您可以按 createdDate
升序排序:
array_multisort(array_column($data, 'createdDate'), SORT_ASC, $data);
然后你可以在 UserID
上提取和索引,这只会保留最后一个:
$result = array_column($data, null, 'UserID');
如果你想重建索引(不需要):
$result = array_values($result);