Home > Software design >  PHP - How to combine array with same key
PHP - How to combine array with same key

Time:10-12

I have an arrays like this. I want to combine and group all the same key

Array
    (
        [threeMonths] => Array
            (
                [August] => 87
                [June] => 88
                [October] => 20
                [September] => 73
                [July] => 50
            )
    
        [sixMonth] => Array
            (
                [September] => 72
                [June] => 105
                [October] => 31
                [August] => 71
                [July] => 102
            )
    
        [twelveMonths] => Array
            (
                [August] => 41
                [September] => 53
                [June] => 13
                [July] => 30
                [October] => 15
            )
    
    )

I need to get them in this format:

$array =>(
    [June] => (88,105,13)
    [July] => (50,102,30)
    [August] => (87,71,41,)
    [September] => (73,72,53)
    [October] => (20,31,15)

)

How can I achieve this? I'm using Laravel as my backend framework.

CodePudding user response:

You will just create function for that

$dataArray = [$array1, $array2, $array3];
$data = [];

foreach ($dataArray as $array) {
    if (is_array($array)) {
        foreach($array as $key => $value) {
            if (isset($data[$key])) {
                array_push($data[$key], $value);
            } else {
                $data[$key] = [$value];
            }
        }
    }
}

// Your result in $data

CodePudding user response:

You can use array_merge_recursive for this.

$new = array_merge_recursive($array['threeMonths'],$array['sixMonth'],$array['twelveMonths']);

or

$arrayVal = array_values($array);
$new = array_merge_recursive(...$arrayVal);

The result is a structure like this:

array (
  'August' => 
  array (
    0 => 87,
    1 => 71,
    2 => 41,
  ),
  'June' => 
  array (
    0 => 88,
    1 => 105,
    2 => 13,
  ),
  'October' => 
  array (
    0 => 20,
    1 => 31,
    2 => 15,
  ),
  'September' => 
  array (
    0 => 73,
    1 => 72,
    2 => 53,
  ),
  'July' => 
  array (
    0 => 50,
    1 => 102,
    2 => 30,
  ),
)

if the subarrays are to be brought into a different shape, this can be done with implode.

  • Related