如何通过在php中操作两个数组来获取信息?

时间:2014-05-19 08:28:52

标签: php arrays

我有两个阵列一个用于当前列表,另一个用于总讲座。我想要一个能保持两个百分比的第三个数组

我的第一个阵列(现在的日期列表)

$allpresentAttInfo = array(
        0 => array(
           'year' => '2013',
           'term' => 'T1',
           'presentDays' => '123' 
        ),
        1 => array(
           'year' => '2013',
           'term' => 'T2',
           'presentDays' => '112'
        )
    );

我的第二个数组(总天数列表)

$allAttInfo = array(
        0 => array(
           'year' => '2013',
           'term' => 'T1',
           'totalDays' => '200' 
        ),
        1 => array(
           'year' => '2013',
           'term' => 'T2',
           'totalDays' => '216'
        )
    );

我的结果数组应该是这样的

 $attInfo = array(
        0 => array(
            'year' => '2013',
            'term' => 'T1',
            'presentPercent' => '63.7 %'
        ),
        1 => array(
            'year' => '2013',
            'term' => 'T2',
            'presentPercent' => '42.7 %'
        )
    );

因此,通过合并两个数组,我将不得不在给定的年份和期限内找到当前的数据。如何在PHP端实现这一点。提前致谢

1 个答案:

答案 0 :(得分:0)

非常感谢大家......我很着急,所以寻找一些快捷的复制粘贴方式...我编码了。但如果可以的话,仍然给我一些性能优化。

我的解决方案是。

$attInfo = array();
    foreach ($allAttInfo as $allatt) {
        foreach ($allpresentAttInfo as $allpre) {
                if($allpre['year'] == $allatt['year'] && $allpre['term'] == $allatt['term']){
                   $presentPercent = round(($allpre['presentDays'] / $allatt['totalDay'])*100,2) . "%";
                   $newArray=array('year'=>$allpre['year'],'term'=>$allpre['term'],'presentPercent'=>$presentPercent);
                   array_push($attInfo, $newArray);
            }
        }
    }