1

I'm trying to add a key and value (associative) from an array to another array, where one specific key and value match. Here are the two arrays:

$array1 = array(
            1 => array(
                'walgreens' => 'location',
                'apples' => 'product1',
                'oranges' => 'product2'
            ),
            2 => array(
                'walmart' => 'location',
                'apples' => 'product1',
                'oranges' => 'product2',
                'milk' => 'product3'
            )
       );
$array2 = array(
            1 => array(
                'walgreens' => 'location',
                'apples' => 'product1',
                'oranges' => 'product2',
                'bananas' => 'product3',
            )
      );

Here is the attempt I made at modifying $array1 to have key 'bananas' and value 'product3':

$dataCJ = getCJItem($isbn);
         foreach ($array1 as $subKey => $subArray) {
            foreach($subArray as $dkey => $dval){
                foreach($array2 as $cjk => $cjv){
                    foreach($cjv as $cjkey => $cjval){
                         if($dval['walgreens'] == $cjval['walgreens']){
                              $dval['bananas'] = $cjval['bananas'];
                         }
                    }
                }
            }
         }

This doesn't work. How can I fix this?

2
  • What output do you want for your input example? Commented Aug 3, 2012 at 20:41
  • Hard to workout without output format required.. Commented Aug 3, 2012 at 20:58

2 Answers 2

3

Change => $dval to => &$dval. Currently you are creating and writing to a new variable and the update will not work in-place.

Sign up to request clarification or add additional context in comments.

Comments

2

I would look at array_merge() function!

Here is a start with the PHP doc.


For your specific case, you could do the following :

foreach($array1 as $key1 => $values1){
    foreach($array2 as $key2 => $values2){
        if($values1[0] == $values2[0]){
            $array1[$key1] = array_merge($values1, $values2);
        }
    }
}

Note to simplify the problem you should inverse the first key=> value pair of the array.

Having an array this way would be a lot simper :

array(
    'location' => "The location (eg:walgreens)",
    //...
);

This way you could change the comparison to the following instead :

$values1['location'] == $values2['location']

Which would be safer in the case the array is not built with the location as the first pair.

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.