php group array by key
How to group an array of associative arrays by key in PHP
Read this article in other language
Sometimes, the group by function of SQL won’t be enough to group some data according to your needs. Whatever the reason is, you will be able anyway to group the data as you want with the programming language of your preference. For example, in PHP it’s possible to group an associative array by some key, so you will be able to display it’s data by some order (group).
In this article, we’ll share with you a tiny snippet that allows you to group items of an array by some key.
Group by function
The following function creates a new array that stores all the data of the original input array with an associative structure. It iterates once, creating a new key for the new array with the value of the data with the specified key (so when a new item with the same value appears, it will be pushed into this key). If an item of the input array doesn’t contain the defined key, it will be pushed into the empty string key of the new array:
Usage
Consider the following data structure:
We have 4 simple items and we want to group them by a single property, for example the gender, so our code to group our data by that key would be:
The dumped array would have the following structure:
As you can see, you will receive a new associative array with all the possible values of the selected key (in this case gender) of your data, so we have 2 groups namely Male and Female. You’ll observe the same logic if you group by another property, for example the city:
array_combine
array_combine — Создаёт новый массив, используя один массив в качестве ключей, а другой для его значений
Описание
Создаёт массив ( array ), используя значения массива keys в качестве ключей и значения массива values в качестве соответствующих значений.
Список параметров
Массив ключей. Некорректные значения для ключей будут преобразованы в строку ( string ).
Возвращаемые значения
Ошибки
Примеры
Пример #1 Простой пример использования array_combine()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 21 notes
If two keys are the same, the second one prevails.
But if you need to keep all values, you can use the function below:
Further to loreiorg’s script
in order to preserve duplicate keys when combining arrays.
I have modified the script to use a closure instead of create_function
Reason: see security issue flagged up in the documentation concerning create_function
// If they are not of same size, here is solution:
// Output
// Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona
// [AR] => Arkansas )
?>
This will seem obvious to some, but if you need to preserve a duplicate key, being you have unique vars, you can switch the array_combine around, to where the vars are the keys, and this will output correctly.
This [default] formula auto-removes the duplicate keys.
This formula accomplishes the same thing, in the same order, but the duplicate «keys» (which are now vars) are kept.
I know, I’m a newbie, but perhaps someone else will need this eventually. I couldn’t find another solution anywhere.
I was looking for a function that could combine an array to multiple one, for my MySQL GROUP_CONCAT() query, so I made this function.
I needed a function that would take keys from one unequal array and combine them with the values of another. Real life application:
Select 4 product types.
Each product has a serial.
There are 4 sets of products.
Array
(
[0] => Array
(
[SMART Board] => serial to smart board1
[Projector] => serial to projector 1
[Speakers] => serial to speakers 1
[Splitter] => serials to splitter 1
)
[1] => Array
(
[SMART Board] => serials to smart board 2
[Projector] => serials to projector 2
[Speakers] => serials to speakers 2
[Splitter] => serials to splitter 2
)
Sort/group array by key
TL;DR
Sort/group array by key without adding another level to the array (data parsed by jQuery plugin)?
Details
I am building an array to return to some DOM element.
It takes in CC (engine size stuff) as a parameter and uses that as a key, the problem lies with sorting the array after.
Let’s say, user selects this range of CC’s:
50 has 32 options available
100 has 3 options available
125 has 12 options available
My current code loops through the CC’s, executes the SQL to get the options and using a loop counter creates the key like this:
The problem is that
50 with 32 goes upto 5031 as a key. 100 with 3 goes upto 1002 as a key. 125 with 12 goes upto 12511 as a key.
By now hopefully you can clearly see the issue. 5031 is greater than 1002. So options for 50cc with a loop counter passed 9 is greater than 100cc options.
(just for clarity, example output is):
50cc Option 1
50cc Option 2
50cc Option 3
50cc Option 4
50cc Option 5
100cc Option 1
100cc Option 2
100cc Option 3
50cc Option 6
50cc Option 7
Maybe the initial problem is how I’m creating the keys, but I’ve tried to use ksort with a few different flags to try and achieve my goal but none of the flags seem to target what I’m after:
How do I sort/group my keys without adding another level to my array (the data is parsed by a jQuery plugin that needs the data in a certain format)?
How to group subarrays by a column value?
I have the following array
On the above example id have 2 items, so its need to be inside of the id
17 Answers 17
There is no native one, just use a loop.
You can try the following:
In a more functional programming style, you could use array_reduce
Consume and cache the column value that you want to group by, then push the remaining data as a new subarray of the group you have created in the the result.
$fldName = Group By Colum Name;
If you desire a Composer alternative with a full suite of tests, the array_group_by function achieves what you are looking for. Full disclosure: I am the author of said library.
It also supports multi-level groupings, or even complex grouping through use of custom callback functions:
Expanding on @baba’s answer, which I like, but creates a more complex three level deep multi-dimensional (array(array(array))):
96 has a part no. of reterty and shipping number of 212755-1
96 has a part no. of dftgtryh and shipping number of 212755-1
It’s trivial to do with LINQ, which is implemented in PHP in several libraries, including YaLinqo*. It allows performing SQL-like queries on arrays and objects. The groubBy function is designed specifically for grouping, you just need to specify the field you want to group by:
The result will be exactly like in the accepted answer, just with less code.
1. GROUP BY one key
2. Detecting the unique rows for a table (twodimensional array)
The strategy is simple: Make from the original array a shallow array, where the elements are implode d «columns» of the original array; then apply array_unique(. ) on it; and as last use the detected IDs for filtering of the original array.
3. Detecting the rows with unique identifier columns for a table (twodimensional array)
This solution relies on the 2nd one. Now the complete «row» doesn’t need to be unique. Two «rows» (elements of the first dimension) are equal now, if all relevant «fields» (elements of the second dimension) of the one «row» are equal to the according «fields» (elements with the same key).
The «relevant» «fields» are the «fields» (elements of the second dimension), which have key, that equals to one of the elements of the passed «identifiers».
Функции для работы с массивами
Содержание
User Contributed Notes 14 notes
A simple trick that can help you to guess what diff/intersect or sort function does by name.
Example: array_diff_assoc, array_intersect_assoc.
Example: array_diff_key, array_intersect_key.
Example: array_diff, array_intersect.
Example: array_udiff_uassoc, array_uintersect_assoc.
This also works with array sort functions:
Example: arsort, asort.
Example: uksort, ksort.
Example: rsort, krsort.
Example: usort, uasort.
?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>
Updated code of ‘indioeuropeo’ with option to input string-based keys.
Here is a function to find out the maximum depth of a multidimensional array.
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)
Short function for making a recursive array copy while cloning objects on the way.
If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.
to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);
You can also stringify objects, numbers, etc.
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:
I was looking for an array aggregation function here and ended up writing this one.
Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.