Home > Blockchain >  Merge with count for key value pair in associative array
Merge with count for key value pair in associative array

Time:04-13

I have this array and I want to combine the y_axis if the x_axis is the same, please see both examples so you will have an idea of what I need.

array:4 [
  0 => array:2 [
    "x_axis" => 8
    "y_axis" => 1
  ]
  1 => array:2 [
    "x_axis" => 9
    "y_axis" => 1
  ]
  2 => array:2 [
    "x_axis" => 11
    "y_axis" => 2
  ]
  3 => array:2 [
    "x_axis" => 11
    "y_axis" => 3
  ]
]

Like

array:3 [
  0 => array:2 [
    "x_axis" => 8
    "y_axis" => 1
  ]
  1 => array:2 [
    "x_axis" => 9
    "y_axis" => 1
  ]
  2 => array:2 [
    "x_axis" => 11
    "y_axis" => 5
  ]
]

CodePudding user response:

I wrote a function. Where i include two two loops. First loop create a new array where you calculate the values. The second create the final array where assign the values in the pattern where you need.

<?php

$arr = [
    ['x_axis' => 8, 'y_axis' => 1],
    ['x_axis' => 9, 'y_axis' => 1],
    ['x_axis' => 11, 'y_axis' => 2],
    ['x_axis' => 11, 'y_axis' => 3],
];

function make($arr) {
    $xy = [];
    foreach($arr as $k => $v) {
        
        $xy[$v['x_axis']] = isset($xy[$v['x_axis']]) ?  $xy[$v['x_axis']]   $v['y_axis'] : $v['y_axis'];
    }
    $arrNew = [];
    foreach($xy as $k => $v) {
        $arrNew[] = ['x_axis' => $k,  'y_axis' => $v];
    }   
    return $arrNew;
}

print_r( make($arr) );

output

Array
(
    [0] => Array
        (
            [x_axis] => 8
            [y_axis] => 1
        )

    [1] => Array
        (
            [x_axis] => 9
            [y_axis] => 1
        )

    [2] => Array
        (
            [x_axis] => 11
            [y_axis] => 5
        )

)

  • Related