0

I have a template array:

$templateArray = [
    'apple'=>'green',
    'bags'=>[['small'=>'1.99'],['medium'=>'2.99'],['large'=>'3.99']]
]

I wish to merge that with what a user passes in:

$userArray = [
    'apple'=>'green',
    'banana'=>'yellow',
    'bags'=>[['large'=>'5000']]
]

I use:

array_intersect_key($userArray, $templateArray);

Which produces:

$processedArray = [
    'apple'=>'green',
    'bags'=>[['large'=>'5000']]
]

The issue I am having is that I want to merge the multi bags array to produce:

$processedArray = [
    'apple'=>'green',
    'bags'=>[['small'=>'1.99'],['medium'=>'2.99'],['large'=>'5000']]
]

Is there a way to do this?

panthro
  • 22,779
  • 66
  • 183
  • 324
  • I'm unclear.. to get the result you're showing, I think you just need to switch your parameters around. But what you're _saying_ is that you want to "merge" them, which would produce the combined values of both. – Jake Aug 16 '16 at 18:02
  • 2
    Have you looked into `array_merge_recursive()`? http://php.net/manual/en/function.array-merge-recursive.php – LSerni Aug 16 '16 at 18:05
  • Thanks for array_merge_recursi‌​ve() – panthro Aug 16 '16 at 18:14
  • array_merge_recursi‌‌​​ve() looks good but im getting repeated entries for large – panthro Aug 16 '16 at 18:16
  • The thing that makes this difficult is the extra array layer. Would it be possible to eliminate the extra array and just have the second layer be `['small'=>'1.99','medium'=>'2.99','large'=>'3.99']`? – Don't Panic Aug 16 '16 at 18:25
  • There are ways of removing duplicated values from multidimensional arrays such as http://stackoverflow.com/questions/2442230/php-getting-unique-values-of-a-multidimensional-array. However, the problem with your example is that the data under the same keys are not consistent. The serialized representation of the `$templateArray['bags']` large value is: `a:1:{s:5:"large";s:4:"3.99";}` while the serialized representation of the `$userArray['bags']` large value is: `a:1:{s:5:"large";s:4:"5000";}`. Is there a reason for different types of data being stored under the same key? – War10ck Aug 16 '16 at 18:29
  • If the two arrays were consistent, i.e. the `$userArray['bags']` value was returned as `[['large'=>'3.99']]` like the `$templateArray` then the approach in the question I linked to in my previous comment would work fine, even with the multiple dimensions. – War10ck Aug 16 '16 at 18:31

0 Answers0