PHP如何分组和计算内部数组的元素

时间:2011-11-29 07:04:39

标签: php arrays multidimensional-array

有人可以解释如何从以下数组中获取此结果吗?这是我要找的结果:

Array
(
    [Nov 18, 2011] => Array
        (
            [C] => 2
            [I] => 1
        )

    [Nov 22, 2011] => Array
        (
            [C] => 2
        )

)

这是包含原始数据的数组:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [Nov 18, 2011] => C
                )

            [1] => Array
                (
                    [Nov 18, 2011] => C
                )

            [2] => Array
                (
                    [Nov 18, 2011] => I
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [Nov 22, 2011] => C
                )

            [1] => Array
                (
                    [Nov 22, 2011] => C
                )

        )

)

显示的第一个数组表示内部数组的每个元素的项数,这是我试图从下一个数组中总结的。感谢。

  • 编辑 -

以下是生成上述算法的查询:

$qrybilled = $this->db->query("SELECT tbltc.BILLED FROM tbltc WHERE tbltc.PN = $pn AND tbltc.Y = $taxyear AND tbltc.SCENARIO = $scenario GROUP BY BILLED");
$x = 0; $arr_billed = array();

foreach ($qrybilled->result() as $row) {
$qry3 = $this->db->query("SELECT tbltc.* FROM tbltc WHERE tbltc.PN = $pn AND tbltc.Y = $taxyear AND tbltc.SCENARIO = $scenario AND tbltc.BILLED = '".$row->BILLED."' GROUP BY TC ORDER BY CAT ASC, TC ASC");

    $tmp3 = array();
    foreach ($qry3->result() as $row) {     
        $tmp3[] = array( date("M d, Y",strtotime($row->BILLED)) => $row->CAT);
    }
    $arr_billed3[] = $tmp3; 

}
$data['billed3'] = $arr_billed3; 

2 个答案:

答案 0 :(得分:4)

$arr[0][] = array('Nov 18, 2011'=>'C');
$arr[0][] = array('Nov 18, 2011'=>'C');
$arr[0][] = array('Nov 18, 2011'=>'I');

$arr[1][] = array('Nov 22, 2011'=>'C');
$arr[1][] = array('Nov 22, 2011'=>'C');

$result = array();
foreach($arr as $key=>$value){
    foreach($value as $k=>$v){
        foreach($v as $_k=>$_v){
            if(isset($result[$_k][$_v])){
                $result[$_k][$_v]++;
            }
            else {
                $result[$_k][$_v] =1;
            }
        }
    }
}

数组结果:

print_r($result);

Array
(
    [Nov 18, 2011] => Array
        (
            [C] => 2
            [I] => 1
        )

    [Nov 22, 2011] => Array
        (
            [C] => 2
        )

)

答案 1 :(得分:0)

$food = array('0' => array('orange', 'banana', 'apple','jack'),
              '1' => array('carrot', 'collard', 'pea'));

echo count($food); // output 2

echo count($food[0]) // output 4

echo count($food[1]) // output 3