如何从另一个数组创建一个数组,计算使用PHP发生特定值的次数?

时间:2014-08-25 07:56:35

标签: php arrays matrix

我有一个数组,我希望以特定的形式提取一些值。

    $array1 = array(
            array("techArea01",1995),
            array("techArea03",1996),
            array("techArea01",1995),
            array("techArea09",1998),
            array("techArea09",1995),
            array("techArea02",1997),
            array("techArea01",1995),
            array("techArea02",1999),
            array("techArea09",1995)
        );

但首先我按key = 0和key = 1排序。

    //Select indexes to sort array.
    $sort = array();
    foreach($array1 as $k=>$v) {
        $sort['0'][$k] = $v['0']; //Sort by tech area.
        $sort['1'][$k] = $v['1']; //Sort by priority date.
    }
    //These variables will be used independently below:
    $sortedByTechArea = $array1;
    $sortedByPriorityDate = $array1;

我首先按技术领域排序并排除双重条目:

    //Sort by tech_area asc
    array_multisort($sort['0'], SORT_ASC,$sortedByTechArea);
    $sortedByTechArea = $sortedByTechArea;

    //Exclude duplicated tech areas entries from array.
    $excludeDoubleEntryInTechArea = array();
    foreach ($sortedByTechArea as &$value) {
        if (!isset($excludeDoubleEntryInTechArea[$value['0']]))
        $excludeDoubleEntryInTechArea[$value['0']] =& $value;
    }
    $sortedByTechArea = array_values($excludeDoubleEntryInTechArea);

它给我们以下结果:

$TechAreaWithoutDoubles:
Array
(
[0] => Array
    (
        [0] => techArea01
        [1] => 1995
    )

[1] => Array
    (
        [0] => techArea02
        [1] => 1997
    )

[2] => Array
    (
        [0] => techArea03
        [1] => 1996
    )

[3] => Array
    (
        [0] => techArea09
        [1] => 1995
    )

)

最后,我提取了独特的技术领域:

    $techArea = '';
    foreach ($sortedByTechArea as $subArrayTechArea) {
        $techArea .= "$subArrayTechArea[0]".',<br />';
    }
    echo 'Ordered list of tech areas:<br />';
    echo $techArea,'</pre>';

结果如下:

Ordered list of tech areas:
techArea01,
techArea02,
techArea03,
techArea09,

多年来我做了类似的事情,最后我得到了以下结果:

Ordered list of years:
1995,
1996,
1997,
1998,
1999,

到目前为止,这么好,但我真正想要的是知道技术领域在一年内发生了多少次。所以我做了以下几点:

echo '<pre>How many tech areas per year exist?<br />';
    //Count of tech area per year.
    $result = array();
    foreach ($array1 as $part) {
        $key = implode(', ', $part);
        if( ! array_key_exists ($key, $result)) {
            $result[$key] = 0;
        }
        $result[$key] = $result[$key] + 1;
    }
    foreach ($result as $key => $value) {
        $count[] = $key.",".$value;
    }

    sort($count);
print_r($count);
echo '</pre>';

我们有以下结果:

How many tech areas per year exist?
Array
(
    [0] => techArea01, 1995,3
    [1] => techArea02, 1997,1
    [2] => techArea02, 1999,1
    [3] => techArea03, 1996,1
    [4] => techArea09, 1995,2
    [5] => techArea09, 1998,1
)

因此,我们知道,例如,1995年技术领域01出现了多少次。问题在于,当技术领域没有发生时,它并没有明确告诉我们。 事实上,我正在寻找创建以下矩阵的方法:

     techArea01 | techArea02 | techArea03 | techArea09
1995      3     |      0     |      0     |      2
1996      0     |      0     |      1     |      0
1997      0     |      1     |      0     |      0
1998      0     |      0     |      0     |      1
1999      0     |      1     |      0     |      0

或者更准确地说,以下数组可以解决问题:

$finalArray = array(
                    array(1995, 3, 0, 0, 2),
                    array(1996, 0, 0, 1, 0),
                    etc.
                    array(1999, 0, 1, 0, 0)
              );

我以为我可以使用我在上面创建的有序列表或类似的东西来创建数组,但我不知道如何插入&#34;零&#34;。

还有更优雅的解决方案吗?或者也许有人有另一个想法直接从原始数组获取值?

我将不胜感激。

2 个答案:

答案 0 :(得分:1)

试试这个

 $array1 = array(
            array("techArea01",1995),
            array("techArea03",1996),
            array("techArea01",1995),
            array("techArea09",1998),
            array("techArea09",1995),
            array("techArea02",1997),
            array("techArea01",1995),
            array("techArea02",1999),
            array("techArea09",1995)
        );

$sorted = array();
$areas = array();
array_walk($array1, function($v) use (&$sorted, &$areas){
   if( !isset($sorted[$v[1]]) )
       $sorted[$v[1]] = array();
   $sorted[$v[1]][] = $v[0];
   $areas[] = $v[0];
});

// filter areas
$areas = array_unique($areas);
sort($areas);

// sort year
ksort($sorted);


echo '----' . implode(' ,', $areas) . "\r\n";
foreach($sorted as $year => $data)
{
   echo $year . ' - ';
   $count = array_count_values($data);

   foreach($areas as $area)
   {  
      if( !isset($count[$area]))
      {
          echo '0,';
      } else {
          echo $count[$area].',';
      }
   }
   echo "\r\n";
}

给出

----techArea01 ,techArea02 ,techArea03 ,techArea09
1995 - 3,0,0,2,
1996 - 0,0,1,0,
1997 - 0,1,0,0,
1998 - 0,0,0,1,
1999 - 0,1,0,0,

答案 1 :(得分:0)

我会直接从原始数组中获取值,如下所示:

foreach ($array1 as $ta) {
    // $ta[0] is tech area, $ta[1] is year.
    // index by tech area and then year.
    // the accumulator will count the number per tech area per year
    $finalArray[ $ta[0] ][ $ta[1] ]++;
    // keep an array of years
    $years[ $ta[1] ]++;
}

如果您只想在数据结构中获得结果,您可以这样做以确保所有技术领域都具有所有年份的值:

foreach ($years as $y => $z) {
    foreach ($finalArray as $ta => &$value) {
        if (! array_key_exists($y, $value)) {
            $value[$y] = 0;
        }
    }
}

如果您将结果打印为表格,则可以执行以下操作:

// sort arrays by key
ksort($finalArray);
ksort($years);

// let's say we're printing out a table.
echo "<table>\n<thead><tr><th>Year</th>";

// add the tech areas
foreach ($finalArray as $ta => $value) {
    echo '<th>' . $ta . '</th>';
}
echo "</tr></thead>\n<tbody>";

// now add the data
foreach ($years as $y => $z) {
    echo '<tr><td>' . $y . '</td>';
    foreach ($finalArray as $ta => $value) {
        echo '<tr>';
        if (array_key_exists($y, $value)) {
            echo '<td>' . $value[$y] . '</td>';
        } else {
            echo '<td>0</td>';
        }
    }
    echo "</tr>\n";
}
echo '</tbody></table>';