想象一下,我们有一群学生:
学生:Ben Sam ......
每个学生都在家里有一组书:
书籍:
所以在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"}
那是Sam的,其余的我们有相同的结构。所以山姆是阵列,书籍是阵列,山姆有一系列书籍。 在这个例子中
答案 0 :(得分:1)
如果您有$ 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;
}
}
}
然后在此之后,任何$ books条目的计数为&gt; 1是副本,即
foreach ($books as $key => $value) {
if ($value) > 1) {
echo "Book " . $key . " is a duplicate (" . $value . ")";
}
}
答案 1 :(得分:1)
$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;
}
}