Group Array Values Based on Key in PHP

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'));

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

Group Array Values By Key

$array3 = array();
foreach ( $array1 as $k => $v ) {
if ( !isset($array3[$v]) )
$array3[$v] = array();

$array3[$v][] = $array2[$k];
}

var_dump($array3);

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 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)

How to group array by key in PHP Laravel Builder query

Considering you code, I would use Laravel Collections, to do something like that:

$vehicles = DB::select('call get_vehicles');

return collect($vehicles)
->groupBy('vhc_id')
->map(function ($group) {
return [
'vhc_id' => $group[0]->vhc_id,
'vhc_make' => $group[0]->vhc_make,
'vhc_model' => $group->pluck('vhc_model')
];
})
->values()
->all();

Notice, that the error you got its not about iterating in foreach it's because you are returning a array of stdClass.

// (object) is used to cast the array to stdClass
$x = (object) ['a' => 1, 'b' => 2];

// you CAN'T do that
$x['a'];

// you SHOULD do that
$x->a;

Back to you problem in Laravel, I recommend you to debug using dump or dd (dump and die) Laravel's functions.

$vehicles = DB::select('call get_vehicles');

// dd to see your first vehicle as stdClass
dd($vehicles[0]);

// dd same thing as array
dd((array) $vehicles[0]);

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

Group multidimensional array by key and sum values in PHP

I would do all the necessary math in the loop that reads the data from the database. Something like this:

$ratings = array();
while ($row = $result->fetch_assoc()) {
$name = $row['name'];
if (!isset($ratings[$name])) {
$ratings[$name] = array('count' => 1, 'sum' => $row['rating']);
}
else {
$ratings[$name]['count']++;
$ratings[$name]['sum'] += $row['rating'];
}
}

Then you can just output your table like so:

echo "<table>";
foreach ($ratings as $name => $r) {
echo "<tr><td>$name</td><td>" . round($r['sum'] / $r['count'], 1) . "</td></tr>";
}
echo "</table>";

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 array items by key value adding an associative element with the grouped values

Loop the array and build an temporary associative array with the end date as the key.

Then copy the original array and unset the 'items' and add the new temporary array values.

$a = array("category" => "Music", 
"items" => array(
array("ID" => "1", "start_date" => "2018-11-20", "end_date" => "2018-11-28"),
array("ID" => "2", "start_date" => "2018-11-22", "end_date" => "2018-11-28"),
array("ID" => "3", "start_date" => "2018-11-26", "end_date" => "2018-11-30"),
array("ID" => "4", "start_date" => "2018-11-27", "end_date" => "2018-11-31"),
array("ID" => "4", "start_date" => "2018-11-29", "end_date" => "2018-11-31")
)
);

foreach($a['items'] as $item){
$new[$item['end_date']]['date'] = $item['end_date'];
$new[$item['end_date']][] = $item;
}
$res = $a;
unset($res['items']);
$res['items'] = array_values($new);

var_dump($res);

Output:

array(2) {
["category"]=>
string(5) "Music"
["items"]=>
array(3) {
[0]=>
array(3) {
["date"]=>
string(10) "2018-11-28"
[0]=>
array(3) {
["ID"]=>
string(1) "1"
["start_date"]=>
string(10) "2018-11-20"
["end_date"]=>
string(10) "2018-11-28"
}
[1]=>
array(3) {
["ID"]=>
string(1) "2"
["start_date"]=>
string(10) "2018-11-22"
["end_date"]=>
string(10) "2018-11-28"
}
}
[1]=>
array(2) {
["date"]=>
string(10) "2018-11-30"
[0]=>
array(3) {
["ID"]=>
string(1) "3"
["start_date"]=>
string(10) "2018-11-26"
["end_date"]=>
string(10) "2018-11-30"
}
}
[2]=>
array(3) {
["date"]=>
string(10) "2018-11-31"
[0]=>
array(3) {
["ID"]=>
string(1) "4"
["start_date"]=>
string(10) "2018-11-27"
["end_date"]=>
string(10) "2018-11-31"
}
[1]=>
array(3) {
["ID"]=>
string(1) "4"
["start_date"]=>
string(10) "2018-11-29"
["end_date"]=>
string(10) "2018-11-31"
}
}
}
}

https://3v4l.org/foKL7



Related Topics



Leave a reply



Submit