I created an associative array within an associative array. However, I ran into a problem when I wanted to increment the pay of the elements. The PHP code is as follows:
$assoc_in_assoc['Manager']['name'] ="Jim";
$assoc_in_assoc['Manager']['pay'] = 7000;
$assoc_in_assoc['Manager']['Location'] ="2nd Flooe";
$assoc_in_assoc['Accountant']['name'] ="Mr Mike";
$assoc_in_assoc['Accountant']['pay'] = 4000;
$assoc_in_assoc['Accountant']['Location'] ="Account Office";
$assoc_in_assoc['Accountant']['Special Skills'] ="Charterd Accountant";
// Lets give each one a raise of 1000 dollars
foreach ($assoc_in_assoc as $rec){
echo "<pre>";
$rec['pay'] = $rec['pay']+ 1000;
echo print_r($rec);
echo "</pre>";
}// end for each
echo "<pre>"; echo "<hr/>";
echo print_r($assoc_in_assoc);
echo "</pre>";
?> </body> </html>
Can any one please suggest how to increment the pay with out converting the array structure?
I have solved the problem by changing the structure of the array from Associative into an Associative aray …to an Associative array with in an indexed array.
Solution:
<html> <head> </head> <body> <?php
echo "Associative array with in Associative array";
$assoc_in_assoc['0']['appointment'] ="Manager";
$assoc_in_assoc['0']['name'] ="Jim";
$assoc_in_assoc['0']['pay'] = 7000;
$assoc_in_assoc['0']['Location'] ="2nd Flooe";
$assoc_in_assoc['1']['appointment'] ="Accountant";
$assoc_in_assoc['1']['name'] ="Mr Mike";
$assoc_in_assoc['1']['pay'] = 4000;
$assoc_in_assoc['1']['Location'] ="Account Office";
$assoc_in_assoc['1']['Special Skills'] ="Charterd Accountant";
// Lets give each one a raise of 1000 dollars
$count=0;
foreach ($assoc_in_assoc as $rec){
echo "<pre>";
$assoc_in_assoc[$count]['pay'] += 1000;
$count++;
echo "</pre>";
}// end for each
echo "<pre>"; echo "<hr/>";
echo print_r($assoc_in_assoc);
echo "</pre>";
?> </body> </html>
Can any one please guide me to an exhaustive source of PHP array discussion? Not only the introduction but the detailed explanation of all aspects of arrays.
You could do something else to keep the same structure as before. Instead of doing a simple foreach, you can do the following :