Home > Enterprise >  How to merge arrays in a loop for the same object?
How to merge arrays in a loop for the same object?

Time:06-10

I have

[
    [
        {
            "radius": 0,
            "0004718100": 17.42
        },
        {
            "radius": 1,
            "0004718100": 21.15
        },
    ],
    [
        {
            "radius": 0,
            "0014084415": 21.39
        },
        {
            "radius": 1,
            "0014084415": 22.74
        },
    ]
]

and I need

[
    [
        {
            "radius": 0,
            "0004718100": 17.42,
            "0014084415": 21.39
        },
        {
            "radius": 1,
            "0004718100": 21.15,
            "0014084415": 22.74
        },
    ]
]

my code:

$arr = [];
for ($i = 0; $i < count($data); $i  ) {
     $arr = array_merge($arr, $data[$i]);
}

This merges them continuously into one array instead of adding them to the same objects

CodePudding user response:

How about this ? I did a merge using radius key as the grouping property.

<?php
// example code

$a = [
  0 => [
    0 => [
      'radius' => 0,
      '0004718100' => 17.42,
    ],
    1 => [
      'radius' => 1,
      '0004718100' => 21.15,
    ],
  ],
  1 => [
    0 => [
      'radius' => 0,
      '0014084415' => 21.39,
    ],
    1 => [
      'radius' => 1,
      '0014084415' => 22.74,
    ],
  ],
];


$arr= [];

for ($i = 0; $i < count($a); $i  ) {
    for ($j = 0; $j < count($a[$i]); $j  ) {
        
        $groupingProperty = $a[$i][$j]['radius'];
        
        if (!isset($arr[$groupingProperty])) $arr[$groupingProperty] = [];
        $arr[$groupingProperty] = array_merge($arr[$groupingProperty], $a[$i][$j]);
    }
}


print_r($arr);

CodePudding user response:

What you want to do here is a new array with data being grouped by the radius. So you will need to iterate over the inner elements of your data and check if their radius is already present in the array that you will return. If it isn't => create a NEW ARRAY inside the array you will return and use the radius as an index. If the radius is already present => add the value to the corresponding index (i.e. radius)

CodePudding user response:

$arr = [
    [
        [ 'radius' => 0, '0004718100' => 17.42, ],
        [ 'radius' => 1, '0004718100' => 21.15, ]
    ],
    [
        [ 'radius' => 0, '0014084415' => 21.39, ],
        [ 'radius' => 1, '0014084415' => 22.74, ]
    ]
];

function group_by_radius(array $carry, array $item): array {
  $carry[$item['radius']][] = $item;
  return $carry;
}

$flattened = array_reduce($arr, 'array_merge', []);
$grouped = array_reduce($flattened, 'group_by_radius', []);
$result = array_map(fn($item) => array_merge(...$item), $grouped);
  • Related