Php Grouping Based on a Value

Group array by subarray values

$arr = array();

foreach ($old_arr as $key => $item) {
$arr[$item['id']][$key] = $item;
}

ksort($arr, SORT_NUMERIC);

How to group subarrays by a column value?

There is no native one, just use a loop.

$result = array();
foreach ($data as $element) {
$result[$element['id']][] = $element;
}

Group PHP array elements based on single value in each array

What I believe you want to do is:

$grouped_types = array();

foreach($invalid_results as $type){
$grouped_types[$type['another_id']][] = $type['name'];
}
var_dump($grouped_types);

Output:

array (size=3)
5 =>
array (size=1)
0 => string 'Test 1' (length=6)
3 =>
array (size=3)
0 => string 'Test 2' (length=6)
1 => string 'Test 7' (length=6)
2 => string 'Test 10' (length=7)
2 =>
array (size=1)
0 => string 'Test 3' (length=6)

Group array by values php

Try this :

// Create a new array
$result = array();

// Loop through your array
foreach ($array as $value) {
// Create a key that start at 0
$i = 0;
// Test if $result[0] exist : if yes, you have data, else you have nothing
if (isset($result[$i])) {
do {
// Check if the 'name' is new : if yes, $i++ to check next name
if ($result[$i]['name'] !== $value['name']) $i++;
// If you find similar name, stop here
else break;
} while (isset($result[$i]));
// Just add $result[0] with name and age value
} else {
$result[$i] = array (
'name' => $value['name'],
'age' => $value['age']
);
}
// Now you know the index of result you need to work with
// Just add a new code / group array to your code index
$result[$i][$value['group']][] = array($value['code'], $value['group']);
}

If you do var_dump($result); the output is :

array (size=1)
0 =>
array (size=7)
'name' => string 'John Doe' (length=8)
'age' => string '36' (length=2)
1000 =>
array (size=1)
0 =>
array (size=2)
0 => string '437' (length=3)
1 => string '1000' (length=4)
7777 =>
array (size=2)
0 =>
array (size=2)
0 => string '437' (length=3)
1 => string '7777' (length=4)
1 =>
array (size=2)
0 => string '437' (length=3)
1 => string '7777' (length=4)
4000 =>
array (size=2)
0 =>
array (size=2)
0 => string '437' (length=3)
1 => string '4000' (length=4)
1 =>
array (size=2)
0 => string '437' (length=3)
1 => string '4000' (length=4)
5000 =>
array (size=1)
0 =>
array (size=2)
0 => string '437' (length=3)
1 => string '5000' (length=4)
6000 =>
array (size=2)
0 =>
array (size=2)
0 => string '437' (length=3)
1 => string '6000' (length=4)
1 =>
array (size=2)
0 => string '437' (length=3)
1 => string '6000' (length=4)

EDIT :

To get only group value equal to 7777 and 6000 replace

$result[$i][$value['group']][] = array($value['code'], $value['group']);

by

$group_value = $value['group'] == "7777" || $value['group'] == "6000" ? $value['group'] : "Others";
$result[$i][$group_value][] = array($value['code'], $value['group']);

Now the output of var_dump($result); is :

array (size=1)
0 =>
array (size=5)
'name' => string 'John Doe' (length=8)
'age' => string '36' (length=2)
'Others' =>
array (size=4)
0 =>
array (size=2)
0 => string '437' (length=3)
1 => string '1000' (length=4)
1 =>
array (size=2)
0 => string '437' (length=3)
1 => string '4000' (length=4)
2 =>
array (size=2)
0 => string '437' (length=3)
1 => string '4000' (length=4)
3 =>
array (size=2)
0 => string '437' (length=3)
1 => string '5000' (length=4)
7777 =>
array (size=2)
0 =>
array (size=2)
0 => string '437' (length=3)
1 => string '7777' (length=4)
1 =>
array (size=2)
0 => string '437' (length=3)
1 => string '7777' (length=4)
6000 =>
array (size=2)
0 =>
array (size=2)
0 => string '437' (length=3)
1 => string '6000' (length=4)
1 =>
array (size=2)
0 => string '437' (length=3)
1 => string '6000' (length=4)

Is it what you want?

From an array, group items based on the key value with PHP

$groupByContinent = function(array $list) {
return array_reduce($list, function($grouped, $item) {
$grouped[$item['continent']][] = $item;
return $grouped;
}, []);
};

$groupedByContinent = $groupByContinent($data);

https://3v4l.org/s6X1c

Or:

$groupByProperty = function(array $list, string $property) {
return array_reduce($list, function($grouped, $item) use(&$property) {
$grouped[$item[$property]][] = $item;
return $grouped;
}, []);
};

$groupedByContinent = $groupByProperty($data, 'continent');

https://3v4l.org/Be3HL

Grouping element array php based first character value

Here are two refined methods. Which one you choose will come down to your personal preference (you won't find better methods).

In the first, I am iterating the array, declaring the first character of the lokasi_terakhir value as the key in the $result declaration. If the key doesn't yet exist in the output array then it must be declared / set to 1. After it has been instantiated, it can then be incremented -- I am using "pre-incrementation".

The second method first maps a new array using the first character of the lokasi_terakhir value from each subarray, then counts each occurrence of each letter.

(Demonstrations Link)

Method #1: (foreach)

foreach($array as $item){
if(!isset($result[$item['lokasi_terakhir'][0]])){
$result[$item['lokasi_terakhir'][0]]=1; // instantiate
}else{
++$result[$item['lokasi_terakhir'][0]]; // increment
}
}
var_export($result);

Method #2: (functional)

var_export(array_count_values(array_map(function($a){return $a['lokasi_terakhir'][0];},$array)));
// generate array of single-character elements, then count occurrences

Output: (from either)

array (
'Y' => 1,
'P' => 2,
)

Grouping array based on the key value similarity

I'm basing my answer on two assumptions about how products should be grouped:

  1. Although id_product can be missing, where it is present, it is
    correct and sufficient to match two products; and

  2. For two product names to match, the longest name (name with the most
    words) must contain all of the words in the shortest name (name with
    the fewest words).

Given these assumptions, here is a function to determine if two individual products match (products should be grouped together) and a helper function to get words from names:

function productsMatch(array $product1, array $product2)
{
if (
!empty($product1['id_product'])
&& !empty($product2['id_product'])
&& $product1['id_product'] === $product2['id_product']
) {
// match based on id_product
return true;
}
$words1 = getWordsFromProduct($product1);
$words2 = getWordsFromProduct($product2);
$min_word_count = min(count($words1), count($words2));
$match_word_count = count(array_intersect_key($words1, $words2));
if ($min_word_count >= 1 && $match_word_count === $min_word_count) {
// match based on name similarity
return true;
}
// no match
return false;
}

function getWordsFromProduct(array $product)
{
$name = mb_strtolower($product['name']);
preg_match_all('/\S+/', $name, $matches);
$words = array_flip($matches[0]);
return $words;
}

This function can be used to group the products:

function groupProducts(array $data)
{
$groups = array();
foreach ($data as $product1) {
foreach ($groups as $key => $products) {
foreach ($products as $product2) {
if (productsMatch($product1, $product2)) {
$groups[$key][] = $product1;
continue 3; // foreach ($data as $product1)

}
}
}
$groups[] = array($product1);
}
return $groups;
}

And then this function can be used to extract the shortest name and count for each group:

function uniqueProducts(array $groups)
{
$uniques = array();
foreach ($groups as $products) {
$shortest_name = '';
$shortest_length = PHP_INT_MAX;
$count = 0;
foreach ($products as $product) {
$length = mb_strlen($product['name']);
if ($length < $shortest_length) {
$shortest_name = $product['name'];
$shortest_length = $length;
}
$count++;
}
$uniques[] = array(
'name' => $shortest_name,
'count' => $count,
);
}
return $uniques;
}

So combining all 4 functions, you can get the uniques as follows (tested with php 5.6):

$data[0]['name'] = 'product 1 brandX';
$data[0]['id_product'] = '77777777';
$data[1]['name'] = 'brandX product 1';
$data[1]['id_product'] = '77777777';
$data[2]['name'] = 'brandX product 1 RED';
$data[2]['id_product'] = '77777777';
$data[3]['name'] = 'product 1 brandX';
$data[3]['id_product'] = '';
$data[4]['name'] = 'product 2 brandY';
$data[4]['id_product'] = '8888888';
$data[5]['name'] = 'product 2 brandY RED';
$data[5]['id_product'] = '';

$groups = groupProducts($data);
$uniques = uniqueProducts($groups);
var_dump($uniques);

Which gives output:

array(2) {
[0]=>
array(2) {
["name"]=>
string(16) "product 1 brandX"
["count"]=>
int(4)
}
[1]=>
array(2) {
["name"]=>
string(16) "product 2 brandY"
["count"]=>
int(2)
}
}

Group array values based on key in php?

You could use a generic function:

function _group_by($array, $key) {
$return = array();
foreach($array as $val) {
$return[$val[$key]][] = $val;
}
return $return;
}

I added some sample code to test

<?php

$list= [
[ 'No' => 101,
'Paper_id' => 'WE3P-1',
'Title' => "a1",
'Author' => 'ABC',
'Aff_list' => "University of South Florida, Tampa, United States",
'Abstracts' => "SLA"
] ,
[ 'No' => 101,
'Paper_id' => 'WE3P-1',
'Title' => "a2",
'Author' => 'DEF',
'Aff_list' => "University of South Florida, Tampa, United States",
'Abstracts' => "SLA"
] ,
[ 'No' => 104,
'Paper_id' => 'TUSA-3',
'Title' => "a3",
'Author' => 'GH1',
'Aff_list' => "University of Alcala, Alcala de Henares, Spain",
'Abstracts' => "Microwave"
] ];

print_r(_group_by($list, 'No'));

Group an array based on common value

How about this modify your foreach loop to this:

$list = array();
foreach ($records as $data) {
$code = $data['product_code']; // as key
if (!isset($list[$code])) { // set new array if not exist
$list[$code] = array("product_code" => $code, "product_name" => $data['product_name'], "push" => [], "pull" => []);
}
$subKey = strtolower($data['cha_sty_id']); // get push / pull as new subkey
$list[$code][$subKey][] = $data['chs_name']; // append to the array
}

You can use array_values to remove the code keys from $list after the loop if not needed

Group and merge subarray data based on one column value

A simple loop should do this..

$group = [];
foreach ($data as $item) {
if (!isset($group[$item['date']])) {
$group[$item['date']] = [];
}
foreach ($item as $key => $value) {
if ($key == 'date') continue;
$group[$item['date']][$key] = $value;
}
}


Related Topics



Leave a reply



Submit