Page 1 of 1

Merging Multi-Demensional Arrays

Posted: Tue Nov 28, 2006 4:53 pm
by John Cartwright
As you can see I'm trying to merge two arrays on the first level key. The problem is the values of the second array are not merged as I thought it would.

Code: Select all

$errors['field'] = array();
$errors['field'][] = 'blah';
$errors['field'][] = 'blah2';
$errors['field'][] = 'blah3';

$errors2['field'] = array();
$errors2['field'][] = 'blah33';
$errors2['field'][] = 'blah23';
$errors2['field'][] = 'blah33';

$newerror = array_merge($errors, $errors2);

Code: Select all

Array
(
    [field] => Array
        (
            [0] => blah
            [1] => blah2
            [2] => blah3
        )

)
Burrito mentioned array_merge() doesn't play well with multi-dimensional arrays, so I came up with a quick hack :(

Code: Select all

$field = array_keys($errors2);
foreach ($errors2[$field[0]] as $error)
{
  array_push($errors[$field[0]], $error);
}
This is obviously very ugly, any thoughts of an easier way? I know I must be complicating things. One of those days...

Posted: Tue Nov 28, 2006 5:02 pm
by feyd
I think someone posted their variant on array_merge_recursive() or some similar name recently... can't recall the username offhand.

Posted: Tue Nov 28, 2006 5:42 pm
by John Cartwright
Damn, I guess if there isn't anytime native that I may have overlooked this will do.

I spent about 15 minutes straight on our search, and couldn't come up with what you had suggested.

Posted: Tue Nov 28, 2006 10:18 pm
by volka

Posted: Tue Nov 28, 2006 11:22 pm
by John Cartwright
I don't think that exactly what I want..

I've tried using it already to the same effect. If you can show me how to use it to this effect, please do :P

Posted: Wed Nov 29, 2006 1:14 am
by volka

Code: Select all

<?php
$errors['field'] = array();
$errors['field'][] = 'blah';
$errors['field'][] = 'blah2';
$errors['field'][] = 'blah3';

$errors2['field'] = array();
$errors2['field'][] = 'blah33';
$errors2['field'][] = 'blah23';
$errors2['field'][] = 'blah33';

$newerror = array_merge_recursive($errors, $errors2); 
var_export($newerror);

Code: Select all

array (
  'field' => 
  array (
    0 => 'blah',
    1 => 'blah2',
    2 => 'blah3',
    3 => 'blah33',
    4 => 'blah23',
    5 => 'blah33',
  ),
)
What do you want it to do?

Posted: Wed Nov 29, 2006 2:13 am
by John Cartwright
To tell you the truth, I had a typo when testing recursive.

Thanks for the help :D

Posted: Wed Nov 29, 2006 4:21 am
by Ollie Saunders
Yeah I can sympathise JCart. array_merge is a shoddy excuse for a function. The only thing I've done in the past is a foreach just like you.