Group Array by Subarray Values

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

Grouping array group into separate sub array group

If you start with the zeroth element in the array you get [["a"]] and then if you iterate from the first element and just check whether its the same as the previous element you can determine whether to push to the existing last array, or start a new one.

So use slice to get the array except the zeroth element and forEach to accumulate your new array:





let a = ["a", "a", "a", "b", "c", "c", "b", "b", "b", "d", "d", "e", "e", "e"]

var result = [[a[0]]]
a.slice(1).forEach( (e,i) => {
if(e == a[i]) {
result[result.length-1].push(e);
} else{
result.push([e]);
}
});
console.log(result)

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?

Group array rows by column value and create subarrays in each group

You can do this way.

$inputArray = array("0"=>array('record_id'=>'3','task_date'=>'28-10-02'),'1'=>array('record_id'=>'3','task_date'=>'28-10-02'),'2'=>array('record_id'=>'3','task_date'=>'28-10-03'));

$outputArray = array();
foreach($inputArray as $key=>$value){
$outputArray[$value['task_date']][]=$value;
}

print_r(array_values($outputArray));

Group array data by column value and only create indexed subarrays if more than one occurrence

Your desired output array structure seems a little strange and I feel like it would make iterating it more complex than it needs to be -- but oh well.

Iterate the input array, and use the date values as keys to help you to group the data and swiftly determine if a given date is being encountered for the first time. An isset() call is going to be the fastest way forward.

  1. If the date has not been encountered yet, simply store the subarray in the result array and assign it a new key using the date.

  2. If the date has been encountered before, then you can perform another quick check to see if the previously stored data (respective to the given date) has the product_id key -- this means it is an associative array and therefore contains only one "set" of data. In this case, a structure change will need to occur. The existing associative array for that date will need to be merged with the new associative array to form a deeper structure. The end result for this iteration will be that the date's data structure becomes an index two-element array of associative arrays.

  3. After a given date has the new "indexed array of associative arrays" stucture, any subsequent encounters of the date are simply pushed into the indexed array using bracket-syntax.

Code: (Demo)

$array = [
['product_id' => 52, 'date' => '2017-07-28'],
['product_id' => 53, 'date' => '2017-07-30'],
['product_id' => 81, 'date' => '2017-07-26'],
['product_id' => 123, 'date' => '2017-07-30'],
['product_id' => 59, 'date' => '2017-07-26'],
['product_id' => 124, 'date' => '2017-07-30']
];

foreach ($array as $subarray) {
$date = $subarray['date']; // not strictly necessary, but may aid code readability
if (!isset($result[$date])) {
$result[$date] = $subarray; // first encounter means no index
} elseif (isset($result[$date]['product_id'])) { // if associative, make indexed with associative subarrays
$result[$date] = [$result[$date], $subarray]; // second encounter means structural change to indexed subarrays
} else {
$result[$date][] = $subarray; // beyond second encounter means push subarray into indexed structure
}
}
krsort($result); // it appears that you want DESC order
var_export($result);

Output:

array (
'2017-07-30' =>
array (
0 =>
array (
'product_id' => 53,
'date' => '2017-07-30',
),
1 =>
array (
'product_id' => 123,
'date' => '2017-07-30',
),
2 =>
array (
'product_id' => 124,
'date' => '2017-07-30',
),
),
'2017-07-28' =>
array (
'product_id' => 52,
'date' => '2017-07-28',
),
'2017-07-26' =>
array (
0 =>
array (
'product_id' => 81,
'date' => '2017-07-26',
),
1 =>
array (
'product_id' => 59,
'date' => '2017-07-26',
),
),
)

Group array of javascript objects based on value into there own sub array of objects

You could use a closure over a hash table for the same email address and their items.





var data = [{ email: "alex@test.com", fn: "Alex", sn: "McPherson", phone: "01233xxxxx", hours: "40", rate: "20", amount: "200", vat: "60", agency: "test", start: "08/06/2017", end: "10/06/2017" }, { email: "mike@test.com", fn: "Mike", sn: "Mann", phone: "01233xxxxx", hours: "50", rate: "70", amount: "500", vat: "90", agency: "test", start: "08/06/2017", end: "10/06/2017" }, { email: "fred@test.com", fn: "Fred", sn: "Frogg", phone: "01233xxxxx", hours: "80", rate: "90", amount: "800", vat: "100", agency: "test", start: "08/06/2017", end: "10/06/2017" }, { email: "alex@test.com", fn: "Alex", sn: "McPherson", phone: "01233xxxxx", hours: "90", rate: "30", amount: "900", vat: "120", agency: "test", start: "08/06/2017", end: "10/06/2017" }],

result = data.reduce(function (hash) {

return function (r, o) {

if (!hash[o.email]) {

hash[o.email] = [];

r.push(hash[o.email]);

}

hash[o.email].push(o)

return r;

};

}(Object.create(null)), []);


console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

JavaScript - Group array of objects into sub-arrays based on multiple properties

Case 1:





function example1(initData, fieldsArr){  



const output = data.reduce((aggObj, item) => {

const stringId = fieldsArr.map(key => item[key]).join('_');



if (aggObj[stringId]){

aggObj[stringId].push(item);

}

else {

aggObj[stringId] = [item];

}


return aggObj;

}, {})



const outputNoDups = Object.values(output).map(group => {



const sorted = group.sort((a,b) => new Date(a.transaction) < new Date(b.transaction) ? -1 : 1);



return sorted.filter((a, i) => {

if (i == 0) return true;


if (a.amount == sorted[i - 1].amount &&

new Date(a.transaction) - new Date(sorted[i - 1].transaction) <= 45000){

return true;

}



return false;

});

});



return outputNoDups.filter(a => a.length > 1);

}


console.log(example1(data, ['manufacturer', 'category']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script id="initData">

const data = [{

id: 3,

manufacturer: 'audi',

amount: 40,

category: 'leasing',

transaction: '2020-03-02T10:34:30.000Z'

},

{

id: 4,

manufacturer: 'audi',

amount: 40,

category: 'leasing',

transaction: '2020-03-02T10:34:38.000Z'

},

{

id: 1,

manufacturer: 'mercedes',

amount: 20,

category: 'leasing',

transaction: '2020-03-05T12:00:00.000Z'

},

{

id: 7,

manufacturer: 'audi',

amount: 40,

category: 'leasing',

transaction: '2020-03-20T11:00:00.000Z'

},

{

id: 6,

manufacturer: 'mercedes',

amount: 20,

category: 'leasing',

transaction: '2020-03-05T12:00:44.000Z'

},

{

id: 2,

manufacturer: 'volkswagen',

amount: 2,

category: 'credit',

transaction: '2020-03-05T12:00:45.000Z'

},

{

id: 5,

manufacturer: 'audi',

amount: 40,

category: 'leasing',

transaction: '2020-03-02T10:35:17.000Z'

},

];

</script>


Related Topics



Leave a reply



Submit