想象一下我们有一群学生:
学生:本·萨姆·
每个学生家里都有一组书:
书:
- 山姆 ·
- 本 ·
- 瑞安·
所以在 PHP 中,$students数据结构如下所示:
Array
(
[0] => Array
(
[name] => Joe Smith
[books] => Array
(
[0] => A
[1] => B
[2] => C
)
)
)
我们想计算 A 重复了多少次,谁拥有 A B 和 C 等。在 php 中执行此操作的一种方法是这样做:
if (sizeof($potential_entries) > 0) :
for ($j = 0, $potentialsize = sizeof($potential_entries); $j < $potentialsize; ++$j) {
for ($k = 0, $listsize = sizeof($student_book); $k < $listsize; ++$k) {
if ($student_book[$k] == $potential_entry[$k]) :
$match = 1;
$student_book[$k]['like_count']++;
endif;
}
}
这不是很有效,我们宁愿想要一个地图结构或哈希表,php有像perl这样的结构吗?还是我们必须手动构建它们。编辑: 我可以在 PHP 中看到我们有关联数组?您能否举一个在文档中找不到它的示例。对于山姆:
var_dump($potential_entry):
[0]=>array(2) { ["name"]=> string(1) "A" ["id"]=> string(11) "1348"}
[1]=>array(2) { ["name"]=> string(1) "B" ["id"]=> string(11) "1483"}
[2]=>array(2) { ["name"]=> string(1) "C" ["id"]=> string(11) "13"}
[3]=>array(2) { ["name"]=> string(1) "D" ["id"]=> string(11) "1174"}
这是对于山姆,对于其余的,我们有相同的结构。 所以山姆是数组,书是数组,山姆有一堆书。在此示例中
- D 计数=3 山姆·本·瑞安
- 计数=2 山姆·瑞恩
- 等。。。
如果你有$students数组,并且这个数组中的每个条目都有一个称为书籍的书籍数组
$books = array();
for ($i = 0, $count = sizeof($students); $i++) {
foreach ($student[$i]['books'] as $book) {
if (isset($books[$book])) {
$books[$book]++;
} else {
$books[$book] = 1;
}
}
}
在此之后,计数为> 1 的任何$books条目都是重复的,即
foreach ($books as $key => $value) {
if ($value) > 1) {
echo "Book " . $key . " is a duplicate (" . $value . ")";
}
}
$aFullCount = array(); // in this array you will have results of all characters count.
$aCondition = array("A", "B"); // set condition you need to count down here.
$aConditionMatch = array(); // in here you will have all users ids who matched your A + B
if ($aUsers){
foreach ($aUsers as $sUserKey=>$aOneUser){
$aForCondition = array();
if ($aPotentialEntries){
foreach ($aPotentialEntries as $aOnePotentialEntry){
$aForCondition[] = $aOnePotentialEntry["name"];
if (!isset($aFullCount[$aOnePotentialEntry["name"]]))
$aFullCount[$aOnePotentialEntry["name"]] = 1;
else
$aFullCount[$aOnePotentialEntry["name"]]++;
}
}
$aConditionCheck = array_intersect($aForCondition, $aCondition);
if (!array_diff($aConditionCheck, $aCondition))
$aConditionMatch[] = $sUserKey;
}
}