[英]Convert array values into an array
我需要將“array_values”的結果轉換為數組,以便將此數組發送到“calculateAverageScore()”。
代碼從數組中提取第一個數據並用array_values 打印它們,但為了使用函數calculateAverageScore,我需要將array_values 轉換為數組。
$person1 = [
'notes' => [1,2,3]
];
$person2 = [
'notes' => [4,5,6]
];
$data=[$person1,$person2];
foreach ($data as $student) {
// Print the first elements of the array
//I need to convert array_values to an array to send it to the function calculateAverageScore ().
echo array_values($student['notes'])[0];
}
// Calculate the average note of the array that we pass.
function calculateAverageScore($Array) {
$sumNotes = 0;
$numNotes = 0;
foreach ( $Array as $oneNote ) {
$numNotes++;
$sumNotes += $oneNote;
}
return $sumNotes/$numNotes;
}
//Result
// 14
//Expected result
// 2,5 (the result of the average of the first numbers of the array 1 and 4)
我們可以遍歷每個項目並將“分數”數組傳遞給平均求和函數。
'scores' 已經是數組格式了。 下面的函數 ( calculate_average_score
) 使用 php array_sum
函數對數組元素求和。 count
返回數組中元素的數量。 所以要獲得平均值 - 只需將一個除以另一個。
<?php
$people =
[
[
'name' => 'Jim',
'scores' => [1,2,3]
],
[
'name' => 'Derek',
'scores' => [4,5,6]
]
];
function calculate_average_score(array $scores) {
return array_sum($scores)/count($scores);
}
foreach($people as $person)
{
printf(
"%s's average score is %d.\n",
$person['name'],
calculate_average_score($person['scores'])
);
}
輸出:
Jim's average score is 2.
Derek's average score is 5.
或者,我們可以從原始數組創建一個新數組,使用array_column
名稱和分數作為鍵和值。 然后我們可以通過一個帶有array_map
的函數來處理每個值(數組分數):
$name_scores = array_column($people, 'scores', 'name');
$name_averages = array_map('calculate_average_score', $name_scores);
print_r($name_averages);
輸出:
Array
(
[Jim] => 2
[Derek] => 5
)
您不需要調用array_values()
,子array_values()
已經被索引。
$person1 = [
'notes' => [1,2,3]
];
$person2 = [
'notes' => [4,5,6]
];
$data=[$person1,$person2];
foreach ($data as $student) {
$Array[] = $student['notes'][0];
}
// now $Array = [1, 4];
echo calculateAverageScore($Array); // 2.5
這會將所有第一個元素值作為一維數組傳遞給您的自定義函數。
如果你想平均每個人的筆記分數......
foreach ($data as $student) {
echo calculateAverageScore($student['notes']);
}
// displays 2 then 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.