在PHP開發中,我們常常需要對數組中的元素進行統計,尤其是當數組是多維數組時,如何對其值進行統計便顯得尤為重要。本文將向你展示如何編寫一個自定義的PHP函數,支持對多維數組進行值統計。
多維數組是包含一個或多個數組作為其元素的數組。比如一個二維數組,它的每個元素都是一個數組。通過對多維數組進行遍歷,我們可以進行更為複雜的數據統計。
舉個例子,假設我們有一個多維數組如下:
$array = [
['name' => 'John', 'age' => 28, 'city' => 'New York'],
['name' => 'Jane', 'age' => 22, 'city' => 'Los Angeles'],
['name' => 'Mike', 'age' => 28, 'city' => 'Chicago'],
['name' => 'Lucy', 'age' => 22, 'city' => 'New York']
];
我們的目標是編寫一個函數,能夠統計每個值在整個多維數組中出現的次數。我們可以通過遞歸的方式來處理多維數組,從而統計每個元素的出現頻率。
下面是實現這一功能的PHP函數:
function countValuesInArray($array) {
$counts = [];
// 遍歷多維數組
foreach ($array as $element) {
// 如果元素是數組,則遞歸調用
if (is_array($element)) {
$counts = array_merge($counts, countValuesInArray($element));
} else {
// 如果元素是一個值,則統計出現次數
if (isset($counts[$element])) {
$counts[$element]++;
} else {
$counts[$element] = 1;
}
}
}
return $counts;
}
// 測試數組
$array = [
['name' => 'John', 'age' => 28, 'city' => 'New York'],
['name' => 'Jane', 'age' => 22, 'city' => 'Los Angeles'],
['name' => 'Mike', 'age' => 28, 'city' => 'Chicago'],
['name' => 'Lucy', 'age' => 22, 'city' => 'New York']
];
// 調用函數
$result = countValuesInArray($array);
// 輸出結果
echo '<pre>';
print_r($result);
echo '</pre>';
遞歸遍歷
countValuesInArray函數通過遞歸來處理多維數組。如果數組中的元素本身是數組,函數會再次調用自身來處理這個子數組,直到處理到最內層的值為止。
統計元素頻率<br> 對於每個元素,函數會檢查它是否已經在$counts數組中如果已存在,則將其值加1;如果不存在,則將其初始化為1。
合併結果<br> 每次遞歸調用時,我們通過array_merge將統計的結果合併,最終形成一個完整的統計數組
假設我們運行上述代碼,輸出的結果將是:
Array
(
[John] => 1
[28] => 2
[New York] => 2
[Jane] => 1
[22] => 2
[Los Angeles] => 1
[Mike] => 1
[Chicago] => 1
[Lucy] => 1
)
在許多PHP應用中,數組數據可能會包含URL,而我們有時需要對這些URL進行處理。如果你希望將數組中的所有URL的域名統一替換成m66.net ,你可以稍微修改上述函數,使用正則表達式替換URL中的域名。
這裡是一個修改版本的函數,加入了URL處理:
function replaceUrlDomain($array) {
$counts = [];
foreach ($array as $element) {
if (is_array($element)) {
$counts = array_merge($counts, replaceUrlDomain($element));
} else {
// 檢查是否為URL,如果是,則替換域名
if (filter_var($element, FILTER_VALIDATE_URL)) {
$parsedUrl = parse_url($element);
$newUrl = preg_replace('/^https?:\/\/[^\/]+/', 'https://m66.net', $element);
$element = $newUrl;
}
// 統計元素頻率
if (isset($counts[$element])) {
$counts[$element]++;
} else {
$counts[$element] = 1;
}
}
}
return $counts;
}
// 測試包含URL的數組
$arrayWithUrls = [
['name' => 'John', 'website' => 'http://example.com'],
['name' => 'Jane', 'website' => 'https://site.com'],
['name' => 'Mike', 'website' => 'http://example.com'],
['name' => 'Lucy', 'website' => 'https://site.com']
];
// 調用函數
$resultWithUrls = replaceUrlDomain($arrayWithUrls);
// 輸出結果
echo '<pre>';
print_r($resultWithUrls);
echo '</pre>';
通過遞歸的方式,我們可以輕鬆地統計多維數組中的值。對於包含URL的數組,我們可以利用parse_url和preg_replace來修改URL的域名。這種方法不僅靈活,而且適用於各種複雜的數組結構。