这两种方法中的哪一种(array_count_values 或 array_key_exists)在内存消耗、资源使用和代码处理的易用性方面更“友好”。差异是否足够大到可能发生重大性能提升或损失的地方?
如果需要有关如何使用这些方法的更多详细信息,我将解析一个非常大的 XML 文件并使用 simpleXML 将某些 XML 值检索到一个数组中(以存储 URL),如下所示:
$XMLproducts = simplexml_load_file("products.xml");
foreach($XMLproducts->product as $Product) {
if (condition exists) {
$storeArray[] = (string)$Product->store; //potentially several more arrays will have values stored in them
}}
不会将重复值插入到数组中,我正在讨论使用 array_key_exists 或 array_count_values 方法来防止重复值。我了解 array_key_exists 更多,但我的问题是它对资源的友好程度如何?足以显着降低性能?
我更愿意使用 array_count_values 方法,主要是因为除了防止数组中的重复值之外,您还可以轻松地显示每个值中有多少重复值。IE 如果在 storeArray “Ace Hardware” 中有 3 个实例,您可以轻松地在 URL 旁边显示“3”,如下所示:
// The foreach loop builds the arrays with values from the XML file, like this:
$storeArray2[] = (string)$Product->store;
// Then we later display the filter links like this:
$storeUniques = array_count_values($storeArray)
foreach ($storeUniques as $stores => $amts) {
?>
<a href="webpage.php?Keyword=<?php echo $keyword; ?>&features=<?php echo $Features; ?>&store=<?php echo $stores; ?>"> <?php echo $stores; ?> </a> <?php echo "(" . ($amts) . ")" . "<br>";
}
如果这两种方法之间的性能差距很大,我将使用 array_key_exists 方法。但是下面的代码只能防止显示重复值。有没有办法同时显示重复值的数量(对于每个值)?
// The foreach loop builds the arrays with values from the XML file, like this:
$Store = (string)$Product->store;
if (!array_key_exists($Store, $storeArray)) {
$storeArray[$Store] = "<a href='webpage.php?Keyword=".$keyword."&Features=".$features."&store=".$Product->store"'>" . $Store . "</a>";
}
// Then we later display the filter links like this:
foreach ($storeArray as $storeLinks) {
echo $storeLinks . "<br>";
}