Search code examples
phparraysmultidimensional-arraygroupingunique

Group associative rows in a 2d array (with numeric keys) to produce indexed subarrays of unique values in each group


I have this array:

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

What I want is to merge the array like this:

Array (
    [2] => Array( 3, 4 )
    [3] => Array( 5 )
)

This is the code that generates the original array:

$optionValuesArrayContainer = array();

foreach ($item_options as $item_options_data) :
    //$item_options_data["option_sons"] is a json object saved in mysql json
    if (count($item_options_data["option_sons"]) > 0) {
        
        foreach (json_decode($item_options_data["option_sons"]) as $item => $value) :
            //$newd[$item] = $value;
            array_push($optionValuesArrayContainer, array($item => $value));
        endforeach;
    }
endforeach;

print_r($optionValuesArrayContainer);

more description: in the mysql, I have multiple rows. one of the columns in these rows named "option_sons" and its a column of json like:

{
    "2": "3",
    "3": "5"
}

another column:

{
    "2": "4",
    "3": "5"
}

I want to merge the columns from different rows to get array of ONE KEY but multiple different VALUES.


Solution

  • If I understand what you try to do correctly it is merging sub-arrays according to their keys and values if their value are the same so you need to remove one of them. Note: I tried to create an original array with json to show real answer. I hope it is crorect.

    $item_options = [
        ['option_sons' => '{"2":3, "3":5}'],
        ['option_sons' => '{"2":4, "3":5}'],
    ];
    
    $result = [];
    foreach ($item_options as $item_options_data) {
        foreach (json_decode($item_options_data["option_sons"]) as $key => $value) {
            if (!isset($result[$key])) {
                $result[$key] = [];
            }
            
            $result[$key] = array_unique(array_merge($result[$key], [$value]));
        }
    }
    
    echo '<pre>';
    var_dump($result);
    

    We have subarrays so we need two loops but more importantly we need to create result array from our key like the if statement then merge subarrays and get unique values to remove duplicate values.