我在关联数组中创建了一个关联数组。但是,当我想增加元素的工资时,我遇到了一个问题。 PHP代码如下:
$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>
任何人都可以建议如何通过转换阵列结构来增加工资?
我已经通过将数组的结构从Associative更改为Associative aray ...到具有索引数组的关联数组来解决了这个问题。
解决方案:
<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>
任何人都可以引导我查看PHP数组讨论的详尽来源吗?不仅是介绍,还有对阵列各方面的详细解释。
答案 0 :(得分:3)
您可以采取其他措施来保持与以前相同的结构。您可以执行以下操作,而不是执行简单的foreach:
foreach($assoc_in_assoc as $key => $rec){
$assoc_in_assoc[$key]['pay'] += 1000;
}
答案 1 :(得分:2)
我建议你在PHP主页上阅读数组。 http://php.net/manual/en/language.types.array.php
您有两种选择:
首先,foreach
有两个参数!另一个参数是数组的键,它是普通数组的整数索引,是关联数组的键。您可以使用另一个,而不是在第二个示例中跟踪$count
。
foreach ($assoc_in_assoc as $key => $rec){
echo "<pre>";
$assoc_in_assoc[$key]['pay'] = $rec['pay'] + 1000;
echo print_r($rec);
echo "</pre>";
}// end for each
其次,你可以通过引用制作foreach
循环并完成你正在做的事情。
foreach ($assoc_in_assoc as &$rec){
echo "<pre>";
$rec['pay'] = $rec['pay'] + 1000;
echo print_r($rec);
echo "</pre>";
}// end for each