通过数组的解析值计算数组

时间:2015-01-08 09:08:06

标签: php algorithm codeigniter yii

我们如何计算数组中的数组元素。

$course = array(
            array(
                'course_name'=> 'HTML',
                'trainee'=> array(
                                array('trainee_name'=>'Hong Va'),
                                array('trainee_name'=>'Reaksmey SE')
                            )
            ),array(
                'course_name'=> 'Java',
                'trainee'=> array(
                                array('trainee_name'=>'Hong Va'),
                                array('trainee_name'=>'Reaksmey SE'),
                                array('trainee_name'=>'Sok Panha'),
                                array('trainee_name'=>'MAO Vannakpanha')
                            )
              )
);

我想要这样的结果:

HTML(2名受训者)

Java(3名受训者)

4 个答案:

答案 0 :(得分:0)

foreach($course as $c){
    echo $c['course_name']."(".count($c['trainee'])." trainees)";
    echo "<br />";
}

答案 1 :(得分:0)

HTML

$course[0]['trainee'][0]['trainee_name'] // Hong Va
$course[0]['trainee'][1]['trainee_name'] // Reaksmey SE

JAVA

$course[1]['trainee'][0]['trainee_name'] // Hong Va
$course[1]['trainee'][1]['trainee_name'] // Reaksmey SE
$course[1]['trainee'][2]['trainee_name'] // Sok Panha

答案 2 :(得分:0)

只需使用foreach并计算

  <?php
       $result = array(); // to handle with data later
       foreach($course as $arr) {
          $result[$arr['course_name']] = count($arr['trainee']);        
          // for output here
          echo $arr['course_name'].' ('.count($arr['trainee']).' trainees)<br>';
       }

答案 3 :(得分:0)

试试这个 - 它还会根据受训人数使用正确的复数或单数。

foreach ($course as $item)
{
    $count = count($item['trainee']);
    $word = ($count == 1) ? 'trainee' : 'trainees';
    echo $item['course_name'] . " ($count $word)"; 
    echo "<br>";
}