Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get array with same key into one in php

I would like to get the array with same value into one.

This is the array I have

Array
(
    [0] => Array
        (
            [id] => 6
            [name] => role
        )
    [1] => Array
        (
            [id] => 5
            [name] => role
        )
    [2] => Array
        (
            [id] => 3
            [name] => category
        )
    [3] => Array
        (
            [id] => 4
            [name] => category
        )   
)

This is what I want to achieve.

Array
(
     [0] => 5,
     [1] => 6
)
Array
(
     [0] => 4,
     [1] => 3
)  

This is my code

$result = array();
foreach ($items as $key => $value) {
   $name  = $value['name']; 
   $result[$name] = array($value['id']);
}

foreach($result as $key => $val){
  print_r($val);
}  

What I am getting is

Array (
    [0] => 5 
) 
Array (
    [0] => 4 
)

Can anyone here to help me for solving this? Any help really appreciated. Thanks.

like image 961
Jomol MJ Avatar asked Aug 17 '26 22:08

Jomol MJ


2 Answers

$result = array();
foreach ($items as $key => $value) {
   $name = $value['name']; 
   if (!isset($result[$name])) {
       $result[$name] = [];
   }
   $result[$name][] = $value['id'];  
}
print_r($result);
like image 91
u_mulder Avatar answered Aug 20 '26 12:08

u_mulder


Try like this

$result=[];
foreach ($items as $value) {
    $result[$value['name']][] = $value['id'];
}
print_r($result);
like image 20
Bibhudatta Sahoo Avatar answered Aug 20 '26 13:08

Bibhudatta Sahoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!