Home ยป How to group array by same key and value in php?
group-array-by-same-key-and-value-in-php
PHP

How to group array by same key and value in php?

Array grouping

If you have data that needs to be sorted by groups, it’s straightforward when dealing with database data. However, when working with multi-dimensional arrays and you want to group them by a specific key-value pair, you can achieve this by using the following code.

$data = array
(
    array( 'text' => 'X', 'label_id' => 'A1,35' ),
    array( 'text' => 'X', 'label_id' => 'A2,34' ),
    array( 'text' => 'Y', 'label_id' => 'B1,29' ),
    array( 'text' => 'Z', 'label_id' => 'C1,20' ),
    array( 'text' => 'Z', 'label_id' => 'C2,19' ),
    array( 'text' => 'Z', 'label_id' => 'C3,18' )  
);
$tmp = array();
 
foreach($data as $arg)
{
    $tmp[$arg['text']][] = $arg['label_id'];
}
 
$output = array();
 
foreach($tmp as $type => $labels)
{
    $output[] = array(
        'text' => $type,
        'label_id' => $labels
    );
}
 
var_dump($output);

1 Comment

Click here to post a comment

86 − 85 =

  • text ,label_id two values this.How can I group but if this values can be three ?
    for example=>text,label_id,text_id,added_date ..

    and foreach($data as $arg)
    {
    $tmp[$arg[‘text’]][] = $arg[‘label_id’];
    } what is this code?I dont understand.