指导我优化我的PHP代码,用数组中的空数据填充缺失值

时间:2014-02-18 12:04:33

标签: php arrays

我有像

这样的数组
array(
    [0] => array(
              [a] => r1,
              [b] => c1,
              [c] => d1,
           ),
    [1] => array(
              [a] => r1,
              [b] => c1,
              [c] => d2,
           ),
    [2] => array(
              [a] => r1,
              [b] => c1,
              [c] => d3,
           ),
    [3] => array(
              [a] => r1,
              [b] => c2,
              [c] => d1,
           ),
    [4] => array(
              [a] => r1,
              [b] => c2,
              [c] => d3,
           ),
    [5] => array(
              [a] => r1,
              [b] => c3,
              [c] => d1,
           )
)

我得到了像

这样的输出
-------------------------------------
|   C1,D1   |   C1,D2   |   C1,D3   |
-------------------------------------
|     -     |   C2,D2   |     -     |
-------------------------------------
|   C3,D1   |     -     |     -     |
-------------------------------------

请帮我优化代码

我的代码:

$count = 0;
  for($i=1; $i<=3; $i++){
    for($j=1; $j<=3; $j++){
      $data[$count] = array(
        'a'     => '',
        'b'     => 'D'.$j,
        'c'     => 'C'.$i
      );
      for($r=0; $r<9; $r++){
      if(isset($rows[$r]) && $rows[$r]['b'] == 'C'.$i && $rows[$r]['c'] == 'D'.$j) {
        $data[$count] = array(
          'a'       => $rows[$r]['a'],
          'b'       => $rows[$r]['b'],
          'c'       => $rows[$r]['c']
        );
      }
    }
    $count++;
  }
}

1 个答案:

答案 0 :(得分:1)

<?php
for($i=1; $i<=3; $i++)
{
    for($j=1; $j<=3; $j++)
    {
        $newData = null;

        // Avoid multiple calls to $rows[$i] because on each time it must browse the array,
        // use foreach instead. Pass by reference avoids copy of current row
        foreach($rows as & $iRow)
        {
            if($iRow['b'] == 'C'.$i && $iRow['c'] == 'D'.$j)
            {
                // Copy row bvecause it is the same structure
                $newData = $iRow;

                // No need to continue the $rows loop
                break;
            }
        }

        // If no results found
        if ($newData == null)
        {
            $newData = array(
                'a'     => '',
                'b'     => 'D'.$j,
                'c'     => 'C'.$i
                );
        }

        // Auto increment index
        $data[] = $newData;
    }
}