#1
  1. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2008
    Posts
    577
    Rep Power
    181

    Merging Associative Arrays with Overwrite/Append


    Alright, I've been around long enough where I should know how to do this by now. I have worked around this in the past by looping through both arrays and coming up with a third array that contains the appropriate values. So here is my test data...

    PHP Code:
    $defaults = Array(
       
    'attr'=>Array(
          
    'class'=>Array('beta')
          ,
    'id'=>'beta'
       
    )
    );

    $newArray = Array(
      ,
    'attr'=> Array(
            
    'id'=>'test'
      
    ),'style' => Array(
          
    'text-align'=>'left'
      
    )
    );

    //I want the defaults array to change beta to test and append
    //the style on it... so the defaults array ends up looking like

    //Array(id=>test, attr=>Array(class=>Array(beta),id=>test),
    //style=>Array(text-align=>left) 
    I have tried array_merge and adding the arrays together. Adding the arrays appends the style which works but I can't figure out how to overwrite the 'id' value without looping through the array.

    Is there any tips on how to accomplish this more efficiently?
    Last edited by pgrinPDT; October 15th, 2012 at 02:22 PM.
  2. #2
  3. No Profile Picture
    Banned
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    57
    Rep Power
    0
    Hi,

    I fear there is no built-in function for this. I thought of array_merge_recursive(), but this works very different (scalar values are joined in an array instead of overwritten).

    So you'll either have to use a loop or recursion.
  4. #3
  5. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,317
    Rep Power
    7170
    I agree with Jacques, I don't believe there is any built in function with that exact logic. You could file it as a feature request against array_merge_recursive (as an optional parameter), it sounds like something that has a decent chance of getting added eventually.
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around
  6. #4
  7. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2008
    Posts
    577
    Rep Power
    181
    Thanks E-Oreo, Jacques.

IMN logo majestic logo threadwatch logo seochat tools logo