Hướng dẫn how to groupby array in php? - cách nhóm mảng trong php?

1. GROUP BY Một khóa

Hàm này hoạt động như GROUP BY cho mảng, nhưng với một giới hạn quan trọng: chỉ có một nhóm "cột" (

function arrayUniqueByRow(array $table = [], string $implodeSeparator)
{
    $elementStrings = [];
    foreach ($table as $row) {
        // To avoid notices like "Array to string conversion".
        $elementPreparedForImplode = array_map(
            function ($field) {
                $valueType = gettype($field);
                $simpleTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
                $field = in_array($valueType, $simpleTypes) ? $field : $valueType;
                return $field;
            }, $row
        );
        $elementStrings[] = implode($implodeSeparator, $elementPreparedForImplode);
    }
    $elementStringsUnique = array_unique($elementStrings);
    $table = array_intersect_key($table, $elementStringsUnique);
    return $table;
}
1) là có thể.

function arrayUniqueByIdentifier(array $array, string $identifier)
{
    $ids = array_column($array, $identifier);
    $ids = array_unique($ids);
    $array = array_filter($array,
        function ($key, $value) use($ids) {
            return in_array($value, array_keys($ids));
        }, ARRAY_FILTER_USE_BOTH);
    return $array;
}

2. Phát hiện các hàng duy nhất cho một bảng (mảng hai chiều)

Hàm này là để lọc "hàng". Nếu chúng ta nói, một mảng hai chiều là một bảng, thì mỗi phần tử của nó là một hàng. Vì vậy, chúng ta có thể loại bỏ các hàng trùng lặp với chức năng này. Hai hàng (các phần tử của kích thước đầu tiên) là bằng nhau, nếu tất cả các cột của chúng (các phần tử của kích thước thứ hai) bằng nhau. Để tổng hợp của các giá trị "cột" áp dụng: nếu một giá trị thuộc loại đơn giản, chính giá trị sẽ được sử dụng khi so sánh; Mặt khác, loại của nó (

function arrayUniqueByRow(array $table = [], string $implodeSeparator)
{
    $elementStrings = [];
    foreach ($table as $row) {
        // To avoid notices like "Array to string conversion".
        $elementPreparedForImplode = array_map(
            function ($field) {
                $valueType = gettype($field);
                $simpleTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
                $field = in_array($valueType, $simpleTypes) ? $field : $valueType;
                return $field;
            }, $row
        );
        $elementStrings[] = implode($implodeSeparator, $elementPreparedForImplode);
    }
    $elementStringsUnique = array_unique($elementStrings);
    $table = array_intersect_key($table, $elementStringsUnique);
    return $table;
}
2,
function arrayUniqueByRow(array $table = [], string $implodeSeparator)
{
    $elementStrings = [];
    foreach ($table as $row) {
        // To avoid notices like "Array to string conversion".
        $elementPreparedForImplode = array_map(
            function ($field) {
                $valueType = gettype($field);
                $simpleTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
                $field = in_array($valueType, $simpleTypes) ? $field : $valueType;
                return $field;
            }, $row
        );
        $elementStrings[] = implode($implodeSeparator, $elementPreparedForImplode);
    }
    $elementStringsUnique = array_unique($elementStrings);
    $table = array_intersect_key($table, $elementStringsUnique);
    return $table;
}
3,
function arrayUniqueByRow(array $table = [], string $implodeSeparator)
{
    $elementStrings = [];
    foreach ($table as $row) {
        // To avoid notices like "Array to string conversion".
        $elementPreparedForImplode = array_map(
            function ($field) {
                $valueType = gettype($field);
                $simpleTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
                $field = in_array($valueType, $simpleTypes) ? $field : $valueType;
                return $field;
            }, $row
        );
        $elementStrings[] = implode($implodeSeparator, $elementPreparedForImplode);
    }
    $elementStringsUnique = array_unique($elementStrings);
    $table = array_intersect_key($table, $elementStringsUnique);
    return $table;
}
4,
function arrayUniqueByRow(array $table = [], string $implodeSeparator)
{
    $elementStrings = [];
    foreach ($table as $row) {
        // To avoid notices like "Array to string conversion".
        $elementPreparedForImplode = array_map(
            function ($field) {
                $valueType = gettype($field);
                $simpleTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
                $field = in_array($valueType, $simpleTypes) ? $field : $valueType;
                return $field;
            }, $row
        );
        $elementStrings[] = implode($implodeSeparator, $elementPreparedForImplode);
    }
    $elementStringsUnique = array_unique($elementStrings);
    $table = array_intersect_key($table, $elementStringsUnique);
    return $table;
}
5) sẽ được sử dụng.

Chiến lược này rất đơn giản: tạo từ mảng gốc một mảng nông, trong đó các phần tử là "cột" của mảng gốc; sau đó áp dụng

function arrayUniqueByRow(array $table = [], string $implodeSeparator)
{
    $elementStrings = [];
    foreach ($table as $row) {
        // To avoid notices like "Array to string conversion".
        $elementPreparedForImplode = array_map(
            function ($field) {
                $valueType = gettype($field);
                $simpleTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
                $field = in_array($valueType, $simpleTypes) ? $field : $valueType;
                return $field;
            }, $row
        );
        $elementStrings[] = implode($implodeSeparator, $elementPreparedForImplode);
    }
    $elementStringsUnique = array_unique($elementStrings);
    $table = array_intersect_key($table, $elementStringsUnique);
    return $table;
}
7 trên đó; và sử dụng lần cuối, ID được phát hiện để lọc mảng gốc.

function arrayUniqueByRow(array $table = [], string $implodeSeparator)
{
    $elementStrings = [];
    foreach ($table as $row) {
        // To avoid notices like "Array to string conversion".
        $elementPreparedForImplode = array_map(
            function ($field) {
                $valueType = gettype($field);
                $simpleTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
                $field = in_array($valueType, $simpleTypes) ? $field : $valueType;
                return $field;
            }, $row
        );
        $elementStrings[] = implode($implodeSeparator, $elementPreparedForImplode);
    }
    $elementStringsUnique = array_unique($elementStrings);
    $table = array_intersect_key($table, $elementStringsUnique);
    return $table;
}

Cũng có thể cải thiện so sánh, phát hiện lớp của giá trị "cột", nếu loại của nó là

function arrayUniqueByRow(array $table = [], string $implodeSeparator)
{
    $elementStrings = [];
    foreach ($table as $row) {
        // To avoid notices like "Array to string conversion".
        $elementPreparedForImplode = array_map(
            function ($field) {
                $valueType = gettype($field);
                $simpleTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
                $field = in_array($valueType, $simpleTypes) ? $field : $valueType;
                return $field;
            }, $row
        );
        $elementStrings[] = implode($implodeSeparator, $elementPreparedForImplode);
    }
    $elementStringsUnique = array_unique($elementStrings);
    $table = array_intersect_key($table, $elementStringsUnique);
    return $table;
}
3.

function arrayUniqueByRow(array $table = [], string $implodeSeparator)
{
    $elementStrings = [];
    foreach ($table as $row) {
        // To avoid notices like "Array to string conversion".
        $elementPreparedForImplode = array_map(
            function ($field) {
                $valueType = gettype($field);
                $simpleTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
                $field = in_array($valueType, $simpleTypes) ? $field : $valueType;
                return $field;
            }, $row
        );
        $elementStrings[] = implode($implodeSeparator, $elementPreparedForImplode);
    }
    $elementStringsUnique = array_unique($elementStrings);
    $table = array_intersect_key($table, $elementStringsUnique);
    return $table;
}
9 nên ít nhiều phức tạp hơn, Z.B.
function arrayUniqueByMultipleIdentifiers(array $table, array $identifiers, string $implodeSeparator = null)
{
    $arrayForMakingUniqueByRow = $removeArrayColumns($table, $identifiers, true);
    $arrayUniqueByRow = $arrayUniqueByRow($arrayForMakingUniqueByRow, $implodeSeparator);
    $arrayUniqueByMultipleIdentifiers = array_intersect_key($table, $arrayUniqueByRow);
    return $arrayUniqueByMultipleIdentifiers;
}

function removeArrayColumns(array $table, array $columnNames, bool $isWhitelist = false)
{
    foreach ($table as $rowKey => $row) {
        if (is_array($row)) {
            if ($isWhitelist) {
                foreach ($row as $fieldName => $fieldValue) {
                    if (!in_array($fieldName, $columnNames)) {
                        unset($table[$rowKey][$fieldName]);
                    }
                }
            } else {
                foreach ($row as $fieldName => $fieldValue) {
                    if (in_array($fieldName, $columnNames)) {
                        unset($table[$rowKey][$fieldName]);
                    }
                }
            }
        }
    }
    return $table;
}
0.


3. Phát hiện các hàng có cột định danh duy nhất cho bảng (mảng hai chiều)

Giải pháp này dựa vào cái thứ 2. Bây giờ "hàng" hoàn chỉnh không cần phải là duy nhất. Hai "hàng" (các phần tử của kích thước đầu tiên) bây giờ là bằng nhau, nếu tất cả các "trường" có liên quan (các phần tử của chiều thứ hai) của một "hàng" bằng với "các trường" (các phần tử có cùng một khóa).

"Các trường" "có liên quan" là "các trường" (các phần tử của chiều thứ hai), có chìa khóa, tương đương với một trong các yếu tố của "định danh" được truyền.

function arrayUniqueByMultipleIdentifiers(array $table, array $identifiers, string $implodeSeparator = null)
{
    $arrayForMakingUniqueByRow = $removeArrayColumns($table, $identifiers, true);
    $arrayUniqueByRow = $arrayUniqueByRow($arrayForMakingUniqueByRow, $implodeSeparator);
    $arrayUniqueByMultipleIdentifiers = array_intersect_key($table, $arrayUniqueByRow);
    return $arrayUniqueByMultipleIdentifiers;
}

function removeArrayColumns(array $table, array $columnNames, bool $isWhitelist = false)
{
    foreach ($table as $rowKey => $row) {
        if (is_array($row)) {
            if ($isWhitelist) {
                foreach ($row as $fieldName => $fieldValue) {
                    if (!in_array($fieldName, $columnNames)) {
                        unset($table[$rowKey][$fieldName]);
                    }
                }
            } else {
                foreach ($row as $fieldName => $fieldValue) {
                    if (in_array($fieldName, $columnNames)) {
                        unset($table[$rowKey][$fieldName]);
                    }
                }
            }
        }
    }
    return $table;
}

Tìm hiểu cách nhóm một mảng các mảng liên kết bằng một số khóa với PHP.

Đôi khi, nhóm theo chức năng của SQL sẽ không đủ để nhóm một số dữ liệu theo nhu cầu của bạn. Dù lý do là gì, dù sao bạn cũng có thể nhóm dữ liệu như bạn muốn với ngôn ngữ lập trình về sở thích của bạn. Ví dụ: trong PHP, có thể nhóm một mảng kết hợp theo một số khóa, vì vậy bạn sẽ có thể hiển thị dữ liệu của nó theo một số thứ tự (nhóm).

Trong bài viết này, chúng tôi sẽ chia sẻ với bạn một đoạn trích nhỏ cho phép bạn nhóm các mục của một mảng bằng một số chìa khóa.

Nhóm theo chức năng

Hàm sau đây tạo ra một mảng mới lưu trữ tất cả dữ liệu của mảng đầu vào gốc với cấu trúc liên kết. Nó lặp lại một lần, tạo một khóa mới cho mảng mới với giá trị của dữ liệu với khóa được chỉ định (vì vậy khi một mục mới có cùng giá trị xuất hiện, nó sẽ được đẩy vào khóa này). Nếu một mục của mảng đầu vào không chứa khóa được xác định, nó sẽ được đẩy vào phím chuỗi trống của mảng mới:

Cách sử dụng

Xem xét cấu trúc dữ liệu sau:

 1,
        "name" => "Bruce Wayne",
        "city" => "Gotham",
        "gender" => "Male"
    ),
    array(
        "id" => 2,
        "name" => "Thomas Wayne",
        "city" => "Gotham",
        "gender" => "Male"
    ),
    array(
        "id" => 3,
        "name" => "Diana Prince",
        "city" => "New Mexico",
        "gender" => "Female"
    ),
    array(
        "id" => 4,
        "name" => "Speedy Gonzales",
        "city" => "New Mexico",
        "gender" => "Male"
    )
);

Chúng tôi có 4 mục đơn giản và chúng tôi muốn nhóm chúng theo một thuộc tính duy nhất, ví dụ như giới tính, vì vậy mã của chúng tôi để nhóm dữ liệu của chúng tôi theo khóa đó sẽ là:

" . var_export($byGroup, true) . "
";

Mảng bị đổ sẽ có cấu trúc sau:

array (
    'Male' => 
        array (
        0 => 
        array (
            'id' => 1,
            'name' => 'Bruce Wayne',
            'city' => 'Gotham',
            'gender' => 'Male',
        ),
        1 => 
        array (
            'id' => 2,
            'name' => 'Thomas Wayne',
            'city' => 'Gotham',
            'gender' => 'Male',
        ),
        2 => 
        array (
            'id' => 4,
            'name' => 'Speedy Gonzales',
            'city' => 'New Mexico',
            'gender' => 'Male',
        ),
    ),
    'Female' => 
        array (
        0 => 
        array (
            'id' => 3,
            'name' => 'Diana Prince',
            'city' => 'New Mexico',
            'gender' => 'Female',
        ),
    ),
)

Như bạn có thể thấy, bạn sẽ nhận được một mảng kết hợp mới với tất cả các giá trị có thể của khóa đã chọn (trong trường hợp này là giới tính) của dữ liệu của bạn, vì vậy chúng tôi có 2 nhóm là nam và nữ. Bạn sẽ quan sát cùng một logic nếu bạn nhóm theo một tài sản khác, ví dụ như thành phố:

" . var_export($byGroup, true) . "
";

Đầu ra của ai sẽ là:

array (
    'Gotham' => 
        array (
        0 => 
        array (
            'id' => 1,
            'name' => 'Bruce Wayne',
            'city' => 'Gotham',
            'gender' => 'Male',
        ),
        1 => 
        array (
            'id' => 2,
            'name' => 'Thomas Wayne',
            'city' => 'Gotham',
            'gender' => 'Male',
        ),
    ),
    'New Mexico' => 
        array (
        0 => 
        array (
            'id' => 3,
            'name' => 'Diana Prince',
            'city' => 'New Mexico',
            'gender' => 'Female',
        ),
        1 => 
        array (
            'id' => 4,
            'name' => 'Speedy Gonzales',
            'city' => 'New Mexico',
            'gender' => 'Male',
        ),
    ),
)

Mã hóa hạnh phúc!

Làm thế nào để bạn nhóm một mảng?

Các bước để tạo hàm GroupBy, tạo một đối tượng làm giá trị ban đầu cho đối tượng kết quả của chúng tôi. Bên trong mảng giảm, tạo một mảng cho từng giá trị khóa riêng biệt và đẩy ravalue nếu giá trị khóa có trong currentValue.

KSORT PHP là gì?

Hàm ksort () sắp xếp một mảng kết hợp theo thứ tự tăng dần, theo khóa.Mẹo: Sử dụng hàm krsort () để sắp xếp một mảng kết hợp theo thứ tự giảm dần, theo khóa.Mẹo: Sử dụng hàm orort () để sắp xếp một mảng kết hợp theo thứ tự tăng dần, theo giá trị.sorts an associative array in ascending order, according to the key. Tip: Use the krsort() function to sort an associative array in descending order, according to the key. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.

Làm thế nào để bạn tổng hợp các giá trị của một mảng có cùng một khóa trong PHP?

Để tổng hợp các giá trị của một khóa cụ thể (chẳng hạn như Qty) trong mảng, bạn có thể sử dụng bất kỳ khóa nào sau:..
vòng lặp foreach ;.
Array_Sum () và Array_Column ().
mảng_sum () và mảng_map ();
Array_Reduce () ..

Làm thế nào để bạn kiểm tra xem một khóa có tồn tại trong một mảng PHP không?

Hàm ARRAY_KEY_EXISTS () PHP ARRAYarray_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.