Created
November 4, 2023 07:06
-
-
Save katsube/3a833ccda1340fabb43f2833a90ad2bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* ユーザー属性を集計する | |
* | |
*/ | |
//---------------------------------------- | |
// ユーザー属性のデータ | |
//---------------------------------------- | |
$user = [ | |
['id'=>1, 'address'=>'北海道', 'age'=>20], | |
['id'=>2, 'address'=>'神奈川県', 'age'=>30], | |
['id'=>3, 'address'=>'島根県', 'age'=>40], | |
['id'=>4, 'address'=>'北海道', 'age'=>30], | |
['id'=>5, 'address'=>'神奈川県', 'age'=>20] | |
]; | |
//---------------------------------------- | |
// 集計 | |
//---------------------------------------- | |
echo "年齢の集計結果\n"; | |
$shukeiAge = shukeiAge(); | |
foreach($shukeiAge as $age => $count){ | |
printf("%d歳:%d人\n", $age, $count); | |
} | |
echo "\n"; | |
echo "居住地の集計結果\n"; | |
$shukeiAddress = shukeiAddress(); | |
foreach($shukeiAddress as $address => $count){ | |
printf("%s:%d人\n", $address, $count); | |
} | |
echo "\n"; | |
/** | |
* 年齢別の集計 | |
* | |
*/ | |
function shukeiAge(){ | |
global $user; // グローバル変数を関数内で使う | |
$result = [ ]; // 集計結果を格納する配列 | |
// ★ここを回答する★ | |
// この行と上のコメントは削除してください | |
} | |
/** | |
* 居住地別の集計 | |
* | |
*/ | |
function shukeiAddress(){ | |
global $user; // グローバル変数を関数内で使う | |
$result = [ ]; // 集計結果を格納する配列 | |
for( $i=0; $i<count($user); $i++ ){ | |
$address = $user[$i]['address']; // '北海道', '神奈川県'... | |
// すでに集計済みなら +1 | |
if( isset($result[$address]) ){ | |
$result[$address]++; | |
} | |
// 未集計なら1を代入し初期化 | |
else{ | |
$result[$address] = 1; | |
} | |
} | |
// 集計結果を返す | |
// 例:['北海道'=>2, '神奈川県'=>1 ...] | |
return( $result ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment