使用 php 在多维数组中删除和插入重复元素的计数
Remove and insert count of duplicates elements in a multidimensional array using php
我有一套借书的多维数组
数组
(
[0] => 数组
(
[出价] => 1
[开始日期] => 2015-02-03
[标题] => 编程
)
[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"
它不是很漂亮,但它会做你想做的事:
//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);
我有一套借书的多维数组
数组 ( [0] => 数组 ( [出价] => 1 [开始日期] => 2015-02-03 [标题] => 编程 )
[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"
它不是很漂亮,但它会做你想做的事:
//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);