Alia Jain
Alia Jain

Reputation: 19

Compare two associative array and combine both data in php

Unable to get difference associative array with combined data. Those value which is not found in array:4 should be combined with array:2 as like below with count 0:

2=>array:2[
"value" => Occupation
"count" => 0
]

What I have already tried

$datas=[];
        foreach($data as $arrayIndex=>$element){
            $match = false;
            foreach($domains as $key=>$elementToMatch){
                if($element['value'] != $elementToMatch ){
                    $match = true;
                    $counts = ['value'=>$elementToMatch,'count'=>0];
                }
                if($match == true) {
                    break;
                }

            }

            if($match) {
                array_push($datas,$counts);
            }
        }

Please help enter image description here

Upvotes: 0

Views: 41

Answers (1)

Anuj Shrestha
Anuj Shrestha

Reputation: 1004

$values = array_column($array2, 'value');
foreach ($array4 as $item) {
    if ( ! in_array($item, $values, true)) {
        $array2[] = [
            'value' => $item,
            'count' => 0
        ];
    }
}

I just used array_column to get the value of all the value of the array:2 and check if all the value from array:4 are present in that data using in_array

If not present add the missing value with count 0 to array:2

Upvotes: 1

Related Questions