【发布时间】:2012-08-09 03:17:19
【问题描述】:
您好,我正在尝试计算关联数组中重复值的数量,如下所示:
array(3) { [0]=> array(3) { ["Title"]=> string(25) "hello"
["Price"]=> int(50)
["Count"]=> int(1) }
[1]=> array(3) { ["Title"]=> string(35) "world"
["Price"]=> int(50)
["Count"]=> int(1) }
[2]=> array(3) { ["Title"]=> string(25) "hello"
["Price"]=> int(50)
["Count"]=> int(1) } }
正如您在此处看到的,“标题”标签中有一个重复值,我想对它们进行计数并将其添加到“计数”部分。我开始做这样的事情:
$prodArray = array();
// Add the values to the array if it's the first time it occurs.
if (!in_array($row['prodTitle'], $prodArray["Title"]))
{
array_push($prodArray,
array( Title => $row['prodTitle'],
Price => $row['prodPrice'],
Count => 1)
);
}
else
{
//Add one to the count for the current item.
}
问题是我无法通过 in_array 函数访问数组中的“Title”元素。欢迎提出任何建议。
【问题讨论】:
-
对它们进行排序,然后运行一个 foreach 循环,将一个与前者进行比较,并在每次相等时将 1 添加到计数器?
-
你有一个例子吗?
-
好吧,我根本不是专家,但你知道有一些功能可以做到这一点,不需要发明任何东西。这是这些功能的链接php.net/manual/en/array.sorting.php
-
好吧,我已经了解了其中的一些功能,我发现了一些可能有用的东西,它看起来像这个链接上的第一个示例,我只是不完全理解代码,所以如果有人可以的话,我会很感激给我解释一下这个功能。 php.net/manual/en/function.uksort.php
标签: php arrays duplicates associative