Forum Moderators: coopster

Message Too Old, No Replies

Inserting new keys/values in multidimensional arrays

         

zendak

5:24 pm on Nov 16, 2004 (gmt 0)

10+ Year Member




$cats['cpuamd']['basename'] = 'cpuamd';
$cats['cpuamd']['title'] = 'CPU AMD';

$cats['cpuintel']['basename'] = 'cpuintel';
$cats['cpuintel']['title'] = 'CPU Intel';

foreach ($cats as $cat) {
$cat['table'] = 'zz_art_'.$cat['basename'];
$cat['det_table'] = 'zz_det_'.$cat['basename'];
}


The foreach loop is supposed to add two new key/value pairs to each element of the array. This seems to be a less cumbersome method than adding them manually, as in

$cats['cpuamd']['table'] = 'zz_art_cpuamd';
$cats['cpuamd']['det_table'] = 'zz_det_cpuamd';

$cats['cpuintel']['table'] = 'zz_art_cpuintel';
$cats['cpuintel']['det_table'] = 'zz_det_cpuintel';


Unfortunately, this does not seem to have any effect.
I've monitored the array contents via

echo '<pre>';
print_r($cats);
echo '</pre>';

but this only yields

Array
(
[cpuamd] => Array
(
[basename] => cpuamd
[title] => CPU AMD
)

[cpuintel] => Array
(
[basename] => cpuintel
[title] => CPU Intel
)

)


The "table" and "det_table" keys plus their values do not show up. What am I missing?

coopster

6:29 pm on Nov 16, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



It's your foreach loop. What you are doing there is actually creating a whole new array called $cat that has a completely different memory space than $cats. Adding a
print_r($cats); 
print_r($cat);
right after your other would show you what I'm talking about.

Knowing that, you realize you probably want something like...

$cats[$cat]['table'] = 'zz_art_'.$cats[$cat]['basename']; 
$cats[$cat]['det_table'] = 'zz_det_'.$cats[$cat]['basename'];
...but that is going to throw you a warning because you cannot use arrays or objects as keys. Doing so will result in a warning: Illegal offset type. So how do you get them in there? Use array_keys() [php.net] in your foreach loop to return all the keys of the array first and use them accordingly.

foreach (array_keys($cats) as $cat) { 
$cats[$cat]['table'] = 'zz_art_'.$cats[$cat]['basename'];
$cats[$cat]['det_table'] = 'zz_det_'.$cats[$cat]['basename'];
}

Multidimensional arrays are fun, no doubt, but print_r is your friend. Helps you quickly troubleshoot what is going on at any given step in your script.

zendak

11:17 am on Nov 17, 2004 (gmt 0)

10+ Year Member



Thanks for the insight, coopster. I hadn't realized that I wasn't actually accessing the keys of the existing array in my original loop.
array_keys is my new friend :)