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 multiple sub arrays in php

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:

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

$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.

any help please?

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

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