0

How can portions of multidimensional arrays be added to an existing two-dimensional (associative) array?

For example, for an existing associative array with the following elements:

$builder = array();
$builder['builder_id'] =        $source['id'];
$builder['builder_name'] =      $source['name'];
$builder['builder_address'] =   $source['address'];

how can portions of the following multidimensional array:

$selection[$category['category_name']]['item_name'] = $category_general['item_name'];
$selection[$category['category_name']]['item_source'] = $category_general['item_source'];
$selection[$category['category_name']]['item_image'] = $category_general['item_image'];

be appended to create the following structure:

$builder['builder_id']
$builder['builder_name']
$builder['builder_address']
$builder['category_name']
$builder['category_name']['item_name']
$builder['category_name']['item_source']
$builder['category_name']['item_image']

Assignments like this didn't work:

$builder['category_name'] = $selection[$category['category_name']];
$builder['category_name'] = $selection[$category['category_name']][];

Any suggestions?

Thanks!

edit:
@symcbean you are correct. assignment failed due to null element in array being assigned.
@Snowsickle thanks for tip which identified source of problem noted.

pseudonymo
  • 75
  • 1
  • 2
  • 6

2 Answers2

2

The first assignment should work.

$builder['category_name'] = $selection[$category['category_name']];

will assign all values contained in the array $selection[$category['category_name']] to the array $builder['category_name'].

DEMO

Alex Kalicki
  • 1,533
  • 9
  • 20
  • PHP Error received when using this assignment method: `A PHP Error was encountered` `Severity: Notice` `Message: Undefined index: Residential & Commercial` `Filename: controllers/cron.php` `Line Number: 238` – pseudonymo Aug 15 '12 at 21:13
  • 1
    Snowsickle is correct. If you get that error then the assignment you've shown in the second block of code in your question will fail too - and it the reason it fails is due to the contents of the $category array - not the method for combining the arrays. – symcbean Aug 15 '12 at 21:24
  • @pseudo, please so a [var_dump()](http://php.net/manual/en/function.var-dump.php) of both the $selection and $builder arrays and edit your question with the result. – Alex Kalicki Aug 15 '12 at 21:40
0

The assignment should work.. but if you need an alternative method:

foreach($selection[$category['category_name']] as $key => $value)
{
    $builder['category_name'][$key] = $value;
}

But once again, assignment with arrays has always worked for me.

trevorkavanaugh
  • 340
  • 1
  • 8