1

I have two array like below:

$array1 = array(
               [0]=>array([0]=>a_a [1]=>aa)
               [1]=>array([0]=>b_b [1]=>bb) 
               [3]=>array([0]=>c_c [1]=>cc) 
               )


$array2 = array(
               [0]=>array([0]=>aa [1]=>AA)
               [1]=>array([0]=>bb [1]=>BB) 
               [3]=>array([0]=>cc [1]=>CC) 
               )

what i would like to merge or overlap to output like below:

$result = array(
               [0]=>array([0]=>a_a [1]=>AA)
               [1]=>array([0]=>b_b [1]=>BB) 
               [3]=>array([0]=>c_c [1]=>CC) 
               )

either output like below:

$result = array(
               [0]=>array([0]=>a_a [1]=>aa [2]=>AA)
               [1]=>array([0]=>b_b [1]=>bb [2]=>AA) 
               [3]=>array([0]=>c_c [1]=>cc [2]=>AA) 
               )

how i do this thing what is the best way any suggestion.

2 Answers 2

1

I don;t know which is the best way but you could do this with two loops. Example:

$result = array();
foreach($array1 as $val1) {
    foreach($array2 as $val2) {
        if($val1[1] == $val2[0]) {
            $result[] = array($val1[0], $val1[1], $val2[1]);
        }
    }
}

echo '<pre>';
print_r($result);

For the first result, its easily modifiable:

$result[] = array($val1[0], $val2[1]);
Sign up to request clarification or add additional context in comments.

1 Comment

@codemania oh okay, i thought you said either, i just preferred the second one, anyway, check the revision
0

you can use this function

1st output :

function my_array_merge(&$array1, &$array2) {
    $result = array();
    foreach($array1 as $key => &$value) {
        $result[$key] = array_unique(array_merge($value, $array2[$key]));
    }
    return $result;
}
$arr = my_array_merge($array1, $array2);

2st output :

function my_array_merge(&$array1, &$array2) {
    $result = array();
    foreach($array1 as $key => &$value) {
        $result[$key] = array_merge(array_diff($value, $array2[$key]), array_diff($array2[$key],$value));
    }
    return $result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.