Group subarrays by one column, make comma-separated values from other column within groups
There should be more elegant solutions, but simplest one I can think of would be this.
// The data you have pasted in the question
$data = [];
$groups = [];
// Go through the entire array $data
foreach($data as $item){
// If the key doesn't exist in the new array yet, add it
if(!array_key_exists($item[1], $groups)){
$groups[$item[1]] = [];
}
// Add the value to the array
$groups[$item[1]][] = $item[0];
}
// Create an array for the data with the structure you requested
$structured = [];
foreach($groups as $group => $values){
// With the array built in the last loop, implode it with a comma
// Also add the 'key' from the last array to it ($group)
$structured[] = [implode(',', $values), $group];
}
I haven't tested this but something similar should do the trick. This simply goes through the given array and collects all entries in a structurized manner (so $groups
variable will contain an array entry for each group sharing a key, and the key will correspond to the 2nd item in each item within the given array). From there it's just about restructuring it to get the format you have requested.
http://php.net/manual/en/control-structures.foreach.php
How to make array unique by one value and others in comma separated?
You can do this in one loop but I prefer to do it in two loops as it will be easier to get the correct output with implode than adding commas and then removing them again.
Loop the array and build an associative array and make an array to collect the numbers.
Then loop again and implode the numbers to a string.
foreach($arr as $sub){
$res[$sub['name']]['name'] = $sub['name'];
$res[$sub['name']]['number'][] = $sub['number'];
}
foreach($res as &$sub){
$sub['number'] = implode(",", $sub['number']);
}
$res = array_values($res);
var_dump($res);
https://3v4l.org/PbGsu
How to store column data as comma separated values when finding duplicate values in another column?
implode()
is not going to be part of a simple/direct solution. You should assign temporary keys using the product values so that you can determine, during each iteration, if you are dealing with the first occurrence (store the whole subarray) or a subsequent occurrence of a product (append/concatenate the new company value using a comma as glue).
When finished iterating, re-index the array with array_values()
.
Code: Demo
$array = array (
0 =>
array (
'company' => 1,
'product' => 5,
),
1 =>
array (
'company' => 2,
'product' => 4,
),
2 =>
array (
'company' => 6,
'product' => 5,
),
3 =>
array (
'company' => 2,
'product' => 3,
),
);
foreach ($array as $set) {
if (!isset($result[$set['product']])) {
$result[$set['product']] = $set;
} else {
$result[$set['product']]['company'] .= ",{$set['company']}";
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'company' => '1,6',
'product' => 5,
),
1 =>
array (
'company' => 2,
'product' => 4,
),
2 =>
array (
'company' => 2,
'product' => 3,
),
)
Group rows of data and in each group sum one column and concatenate another column
I would create an intermediary array which groups into array keys by id
first, then use that to call combinations of array_column()
with array_sum()
and implode()
to produce your sum value
and combined name
string.
$temp_array = [];
foreach ($the_array as $init) {
// Initially, group them on the id key as sub-arrays
$temp_array[$init['id']][] = $init;
}
$result = [];
foreach ($temp_array as $id => $arr) {
// Loop once for each id ($temp_array has 2 elements from your sample)
// And add an element to $result
$result[] = [
'id' => $id,
// Sum the value subkeys
// array_column() returns just the key 'value' as an array
// array_sum() adds them
'value' => array_sum(array_column($arr, 'value')),
// implode the name subkeys into a string
'name' => implode(',', array_column($arr, 'name'))
];
}
print_r($result);
Array
(
[0] => Array
(
[id] => 1
[value] => 60
[name] => apple,orange,banana
)
[1] => Array
(
[id] => 2
[value] => 300
[name] => car,bicycle
)
)
Collapse / concatenate / aggregate a column to a single comma separated string within each group
Here are some options using toString
, a function that concatenates a vector of strings using comma and space to separate components. If you don't want commas, you can use paste()
with the collapse
argument instead.
data.table
# alternative using data.table
library(data.table)
as.data.table(data)[, toString(C), by = list(A, B)]
aggregate This uses no packages:
# alternative using aggregate from the stats package in the core of R
aggregate(C ~., data, toString)
sqldf
And here is an alternative using the SQL function group_concat
using the sqldf package :
library(sqldf)
sqldf("select A, B, group_concat(C) C from data group by A, B", method = "raw")
dplyr A dplyr
alternative:
library(dplyr)
data %>%
group_by(A, B) %>%
summarise(test = toString(C)) %>%
ungroup()
plyr
# plyr
library(plyr)
ddply(data, .(A,B), summarize, C = toString(C))
Group row data by one column value and populate a subarray in each group with the other column value
This should do the trick
$args = array
(
array( 'type' => 'AAA', 'label_id' => 'A1,35' ),
array( 'type' => 'AAA', 'label_id' => 'A2,34' ),
array( 'type' => 'BBB', 'label_id' => 'B1,29' ),
array( 'type' => 'CCC', 'label_id' => 'C1,20' ),
array( 'type' => 'CCC', 'label_id' => 'C2,19' ),
array( 'type' => 'CCC', 'label_id' => 'C3,18' )
);
$tmp = array();
foreach($args as $arg)
{
$tmp[$arg['type']][] = $arg['label_id'];
}
$output = array();
foreach($tmp as $type => $labels)
{
$output[] = array(
'type' => $type,
'label_id' => $labels
);
}
var_dump($output);
The output is :
array
0 =>
array
'type' => string 'AAA' (length=3)
'label_id' =>
array
0 => string 'A1,35' (length=5)
1 => string 'A2,34' (length=5)
1 =>
array
'type' => string 'BBB' (length=3)
'label_id' =>
array
0 => string 'B1,29' (length=5)
2 =>
array
'type' => string 'CCC' (length=3)
'label_id' =>
array
0 => string 'C1,20' (length=5)
1 => string 'C2,19' (length=5)
2 => string 'C3,18' (length=5)
Concatenate values according to the same key value
$array = [
[
'id' => 17,
'drug' => 'Clobazam'
],
[
'id' => 23,
'drug' => 'Dexametasona'
],
[
'id' => 23,
'drug' => 'Diiodohidroxiquinoleína'
],
[
'id' => 25,
'drug' => 'Clobazam'
]
];
$result = [];
foreach ($array as $item) {
$id = $item['id'];
$drug = $item['drug'];
if (isset($result[$id])) {
$result[$id]['drug'] .= ', ' . $drug;
} else {
$result[$id] = $item;
}
}
$result = array_values($result);
var_dump($result);
grouping of array in PHP
Working Solution
<?php
$your_arr = array(
array('id' => 1,'qty' => 5),
array('id' => 2,'qty' => 5),
array('id' => 2222,'qty' => 5),
array('id' => 1,'qty' => 5),
array('id' => 3,'qty' => 5)
);
$new = array();
foreach ($your_array as $r){
if(!isset($new[$r['id']]))$t=0; //check the current id exist in $new if Not $t = 0;
else $t=$r['qty']; //if yes $t's value become the saved value in $new[$r['id']]
$new[$r['id']]['id'] = $r['id'];
$new[$r['id']]['qty'] = ($t+$r['qty']); // add the new value with $new[$r['id]]'s value.
}
echo "<pre>";print_r($new);
?>
Related Topics
Wordwrap/Cut Text in HTML String
Apple Push Notification with Sending Custom Data
Examples of Vulnerable PHP Code
Jetbrains Webide: PHP Variable Type Hinting
How to Add Additional PHP Versions to Mamp
Read Associative Array from JSON in $_Post
Add Allow_Url_Fopen to My PHP.Ini Using .Htaccess
Importing Multiple CSV Files to MySQL Tables
Php: How to Get a List of Classes That Implement Certain Interface
Clean Way to Throw PHP Exception Through Jquery/Ajax and JSON
How to Block Uploads of Nude Images
How to Get All Keys of an Multi Level Associative Arrays in PHP