Hướng dẫn php array group by same value - nhóm mảng php theo cùng một giá trị

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" ($identifier) 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ó (array, object,

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;
}
0,
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) sẽ được sử dụng.

Chiến lược này rất đơn giản: tạo từ mảng ban đầu là 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;
}
3 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à object.

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 nên ít nhiều phức tạp hơn, Z.B.
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;
}
6.


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;
}

Nói chung, chức năng nhóm theo mệnh đề và sum () được sử dụng trong cơ sở dữ liệu để sắp xếp các bản ghi. Nhóm theo bản ghi nhóm tuyên bố theo cùng các giá trị và trả về các bản ghi được lọc. SUM () là một hàm tổng hợp được sử dụng bởi nhóm theo câu lệnh. Nhóm và các hoạt động SUM có thể được tích hợp vào danh sách dữ liệu ở cấp mã trong PHP.

Sử dụng hàm pHP mảng_Reduce () để nhóm theo và tổng các giá trị của một mảng trong PHP. Trong ví dụ này, chúng tôi sẽ chỉ cho bạn cách nhóm mảng theo giá trị khóa và tổng bằng PHP. Nó giúp tổng hợp các giá trị của một mảng có cùng các khóa trong PHP.PHP array_reduce() function to GROUP BY and SUM values of an array in PHP. In this example, we will show you how to group array by key and sum values using PHP. It helps to sum the values of an array with the same keys in PHP.

Trong đoạn mã sau đây, chúng tôi sẽ nhóm mảng theo

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 và tổng các giá trị
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;
}
8 với PHP.

$array = array( 
  array(
    
'id' => 1,
    
'category_id' => 5,
    
'score' => 321
  
),
  array(
    
'id' => 2,
    
'category_id' => 2,
    
'score' => 123
  
),
  array(
    
'id' => 3,
    
'category_id' => 5,
    
'score' => 567
  
),
  array(
    
'id' => 4,
    
'category_id' => 2,
    
'score' => 878
  
),
  array(
    
'id' => 5,
    
'category_id' => 5,
    
'score' => 621
  
)
);
$result array_reduce($array, function($carry$item){
    if(!isset(
$carry[$item['category_id']])){
        
$carry[$item['category_id']] = ['category_id'=>$item['category_id'],'score'=>$item['score']];
    } else {
        
$carry[$item['category_id']]['score'] += $item['score'];
    }
    return 
$carry;
});

Mảng sau đây sẽ trở lại sau nhóm theo và các hoạt động tổng.

Array
(
    [5] => Array
        (
            [category_id] => 5
            [score] => 1509
        )

    [2] => Array
        (
            [category_id] => 2
            [score] => 1001
        )

)

Làm thế nào để nhóm mảng theo giá trị trong PHP?

Sử dụng hàm pHP mảng_Reduce () để nhóm theo và tổng các giá trị của một mảng trong PHP. to GROUP BY and SUM values of an array in PHP.

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

Mảng nhóm trong PHP..
Sử dụng vòng lặp foreach để mảng nhóm bằng một thuộc tính cụ thể trong PHP ..
Sử dụng group_array () để tạo một hàm có thể nhóm một mảng đã cho trong PHP ..

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.