-2

我在关联数组中创建了一个关联数组。然而,当我想增加元素的报酬时,我遇到了一个问题。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>

有人可以建议如何在不转换数组结构的情况下增加工资吗?

我通过将数组的结构从关联更改为关联数组 ... 到索引数组中的关联数组来解决了这个问题。

解决方案:

<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 数组讨论的来源吗?不仅是介绍,还有数组各个方面的详细讲解。

4

2 回答 2

3

您可以做其他事情来保持与以前相同的结构。您可以执行以下操作,而不是执行简单的 foreach:

foreach($assoc_in_assoc as $key => $rec){
    $assoc_in_assoc[$key]['pay'] += 1000;
}
于 2012-08-18T16:24:07.410 回答
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
于 2012-08-18T16:23:59.547 回答