Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge with count for key value pair in associative array

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
  ]
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
        )

)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading