我希望现有数组中的新数组使用key作为旧数组的重复值,将值作为重复计数?

时间:2017-02-22 10:57:13

标签: php arrays laravel codeigniter

我的老阵列

array:7 [
  0 => "22-Feb-2017"
  1 => "22-Feb-2017"
  2 => "22-Feb-2017"
  3 => "27-May-2015"
  4 => "10-May-2015"
  5 => "10-May-2015"
  6 => "08-May-2015"
]

我希望新数组为

array:7 [
  22-Feb-2017 => "3"
  27-May-2015 => "1"
  10-May-2015 => "2"
  08-May-2015 => "1"
]

6 个答案:

答案 0 :(得分:6)

尝试使用array_count_valuesarray_count_values()函数计算数组的所有值。

<?php
$dates = [
    0 => "22-Feb-2017",
    1 => "22-Feb-2017",
    2 => "22-Feb-2017",
    3 => "27-May-2015",
    4 => "10-May-2015",
    5 => "10-May-2015",
    6 => "08-May-2015",
];
$final_array = array_count_values($dates);
print_r($final_array);

<强>输出

Array
(
    [22-Feb-2017] => 3
    [27-May-2015] => 1
    [10-May-2015] => 2
    [08-May-2015] => 1
)

答案 1 :(得分:5)

不确定你是否在寻找类似的东西

http://php.net/manual/en/function.array-count-values.php

答案 2 :(得分:2)

请检查以下输出:

 $a=array(0 => "22-Feb-2017",
    1 => "22-Feb-2017",
    2 => "22-Feb-2017",
    3 => "27-May-2015",
    4 => "10-May-2015",
    5 => "10-May-2015",
    6 => "08-May-2015");

    ///array_count_values counts the same values count////
    $new_array = array_count_values($a);
/// now let's interchange the keys and values////
    foreach($new_array as $key=>$value){
        $out[$value] = $key;
    }

    print_r($out);

答案 3 :(得分:1)

实现目标的一种方式:

$dates = [
    0 => "22-Feb-2017",
    1 => "22-Feb-2017",
    2 => "22-Feb-2017",
    3 => "27-May-2015",
    4 => "10-May-2015",
    5 => "10-May-2015",
    6 => "08-May-2015",
];

$result = [];

foreach ($dates as $date) {
    $result[$date] = array_key_exists($date, $result) ? $result[$date] + 1 : 1;
}

print_r($result);

答案 4 :(得分:1)

这正是您所需要的:

  <?php
    $old_array=array(
        0 => "22-Feb-2017",
        1 => "22-Feb-2017",
        2 => "22-Feb-2017",
        3 => "27-May-2015",
        4 => "10-May-2015",
        5 => "10-May-2015",
        6 => "08-May-2015");

        /*
        Counting the occurances of value & storing it in a new array in the format:
        array("22-Feb-2017"=>3, "27-May-2015"=>2, .........)
        */
        $new_array = array_count_values($a);

        print_r($new_array);

        echo $new_array["22-Feb-2017"];
    ?>

答案 5 :(得分:1)

$data=[0 => "22-Feb-2017",1 => "22-Feb-2017",2 => "22-Feb-2017",3 => "27-May-2015",4 => "10-May-2015",5 => "10-May-2015",6 => "08-May-2015"];
$a=array_count_values($data);

var_dump($a);