使用foreach的二维数组到二维数组

时间:2012-05-31 15:26:22

标签: php foreach

嗨,我有以下数组

array(4) {
  [0]=>
  array(3) {
    ["id_acreditado"]=>
    string(3) "174"
    ["cantidad"]=>
    string(7) "4008.00"
    ["acreditado"]=>
    string(27) "Olga Olivia Lucio Hernandez"
  }
  [1]=>
  array(3) {
    ["id_acreditado"]=>
    string(3) "175"
    ["cantidad"]=>
    string(7) "4008.00"
    ["acreditado"]=>
    string(23) "Enrique Carranco Vences"
  }
  [2]=>
  array(3) {
    ["id_acreditado"]=>
    string(3) "176"
    ["cantidad"]=>
    string(7) "4008.00"
    ["acreditado"]=>
    string(32) "Juana Patricia Contreras Paredes"
  }
  [3]=>
  array(3) {
    ["id_acreditado"]=>
    string(3) "177"
    ["cantidad"]=>
    string(7) "4008.00"
    ["acreditado"]=>
    string(17) "Noemi Cruz Campos"
  }
}

我想创建一个二维数组,其中包含上述数组和不同索引的某些值。我正在使用foreach循环来实现这个目标。

$j=1;
foreach($acreditados as $acreditado){
    $tmp['oneCol'] = $j;
    $tmp['twoCol'] = $acreditado['acreditado'];
    $tmp['threeCol'] = $acreditado['cantidad'];
    $info['fourCol'] =$acreditado['id_acreditado'];
    $info[]=$tmp;
    $j++;
}

$ tmp是一个辅助的一维数组,最近被添加为一个二进制$ info数组的行,但是我没有得到预期的输出。我希望输出如下内容:

array(4) {
      [0]=>
      array(3) {
        ["oneCol"]=>
        int(1)
["twoCol"]=>
        string(27) "Olga Olivia Lucio Hernandez"
        ["threeCol"]=>
        string(7) "4008.00"
["fourCol"]=>
        string(3) "174" 
      }
      [1]=>
      array(3) {
 ["oneCol"]=>
        int(2)
["twoCol"]=>
        string(23) "Enrique Carranco Vences"
        ["threeCol"]=>
        string(7) "4008.00"
["fourCol"]=>
        string(3) "175"
      }
      [2]=>
      array(3) {
 ["oneCol"]=>
        int(3)
       ["twoCol"]=>
        string(32) "Juana Patricia Contreras Paredes"
        ["threeCol"]=>
        string(7) "4008.00"   
 ["fourCol"]=>
        string(3) "176"
      }
      [3]=>
      array(3) {
 ["oneCol"]=>
        int(4)
       ["twoCol"]=>
        string(17) "Noemi Cruz Campos"
        ["threeCol"]=>
        string(7) "4008.00"
 ["fourcol"]=>
        string(3) "177"
      }
    }

1 个答案:

答案 0 :(得分:1)

您遇到代码错误

该行

$info['fourCol'] =$acreditado['id_acreditado'];

应该是

$tmp['fourCol'] =$acreditado['id_acreditado'];

所以代码显示为:(添加了$ tmp数组重置)

$j=1;
foreach($acreditados as $acreditado){
    $tmp = array();
    $tmp['oneCol'] = $j;
    $tmp['twoCol'] = $acreditado['acreditado'];
    $tmp['threeCol'] = $acreditado['cantidad'];
    $tmp['fourCol'] =$acreditado['id_acreditado'];
    $info[] = $tmp;
    $j++;
}