使用php删除并插入多维数组中重复元素的计数

时间:2015-02-04 01:28:14

标签: php arrays multidimensional-array

我有一套借阅书籍的多维数组

阵 (     [0] =>排列         (             [bid] => 1             [begindate] => 2015年2月3日             [title] =>程序设计         )

[1] => Array
    (
        [bid] => 1
        [begindate] => 2015-02-03
        [title] => programming
    )

[2] => Array
    (
        [bid] => 1
        [begindate] => 2015-02-03
        [title] => programming
    )

[3] => Array
    (
        [bid] => 4
        [begindate] => 2015-02-03
        [title] => english
    )

[4] => Array
    (
        [bid] => 4
        [begindate] => 2015-02-04
        [title] => english
    )

[5] => Array
    (
        [bid] => 4
        [begindate] => 2015-02-04
        [title] => english
    )

我已经有了删除重复的代码

0: begindate: "2015-02-03", bid: "1",title: "programming"    
3: begindate: "2015-02-03", bid: "4", title: "english"    
4: begindate: "2015-02-04"bid: "4"title: "english"

我想要的是在该数组中插入重复数,这样我就可以得到这样的结果......

0: begindate: "2015-02-03", bid: "1",title: "programming", count:"3"    
3: begindate: "2015-02-03", bid: "4", title: "english", count:"1"    
4: begindate: "2015-02-04", bid: "4", title: "english", count:"2"

1 个答案:

答案 0 :(得分:0)

它不漂亮,但这会做你想要的:

//main array here is $books
$clean = array();
foreach($books as $k1=>$v1){
    $exists = false;
    //does an entry already exist in $clean?
    foreach($clean as $k2=>$v2){
        if($v1["begindate"]==$v2["begindate"]&&$v1["bid"]==$v2["bid"]&&$v1["title"]==$v2["title"]){
            $exists = $k2;
            break;
        }
    }
    if($exists===false){
        //begin count, insert
        $v1["count"] = 1;
        array_push($clean,$v1);
    }else{
        //increment count
        $clean[$exists]["count"]++;
    }
}
print_r($clean);