合并2个PDO数组并通过共享列进行排序



我有2个不同的查询,返回不同的pdo(fetch_assoc(数组:

$stmt1->execute();
$stmt2->execute();

每个数组都从2个不同的表中返回结果,并带有不同的列,但是它们具有一个共同的列: date ( Timestamp ,该格式以这种格式存储: 2018-04-28 20:31:23 (。是否可以按日期(下降或上升(对结果进行排序以呼应结果排序?

您可以通过合并数组并使用自定义排序函数对结果进行分类。

假设$rows1代表$stmt1的行,$rows2表示$stmt2的行。最终的数组将是:

$rows = array_merge($rows1, $rows2);

现在,您可以使用usort函数对结果数组进行排序:

usort($rows, function (array $r1, array $r2) { ... });

其中 function (array $r1, array $r2)是比较函数。

如果您使用php7比较功能可以是这样的:

function (array $r1, array $r2) {
    $format = 'Y-m-d H:i:s';
    $t1 = DateTimeImmutable::createFromFormat($format, $r1['date']);
    $t2 = DateTimeImmutable::createFromFormat($format, $r2['date']);
    return $t1 <=> $t2;
}

您可以看到,使用太空船运算符进行比较内置DateTimeImmutable类的对象很方便。

对于PHP 5,它将更长一些:

function (array $r1, array $r2) {
    $format = 'Y-m-d H:i:s';
    $t1 = DateTime::createFromFormat($format, $r1['date']);
    $t2 = DateTime::createFromFormat($format, $r2['date']);
    if ($t1 == $t2) {
        return 0;
    }
    return ($t1 > $t2) ? -1 : 1;
}

PHP7的整个示例:

// rows fetched from $stmt1
$rows1 = [
    ['id' => 1001, 'date' => '2018-04-26 08:00:00'],
    ['id' => 1002, 'date' => '2018-04-28 20:11:23'],
    ['id' => 1003, 'date' => '2018-04-28 20:31:23'],
];
// rows fetched from $stmt2
$rows2 = [
    ['id' => 2001, 'date' => '2018-04-27 08:00:00'],
    ['id' => 2002, 'date' => '2018-04-28 20:21:23'],
];
// the resulting array
$rows = array_merge($rows1, $rows2);
// sort the resulting array with our custom sort function
usort($rows, function (array $r1, array $r2) {
    $format = 'Y-m-d H:i:s';
    $t1 = DateTimeImmutable::createFromFormat($format, $r1['date']);
    $t2 = DateTimeImmutable::createFromFormat($format, $r2['date']);
    return $t1 <=> $t2;
});

,输出将按照我们的期望对数组进行排序:

Array
(
    [0] => Array
        (
            [id] => 1001
            [date] => 2018-04-26 08:00:00
        )
    [1] => Array
        (
            [id] => 2001
            [date] => 2018-04-27 08:00:00
        )
    [2] => Array
        (
            [id] => 1002
            [date] => 2018-04-28 20:11:23
        )
    [3] => Array
        (
            [id] => 2002
            [date] => 2018-04-28 20:21:23
        )
    [4] => Array
        (
            [id] => 1003
            [date] => 2018-04-28 20:31:23
        )
)

最新更新