Php 将数组值转换为数组

Php 将数组值转换为数组,php,arrays,Php,Arrays,我需要将“array_values”的结果转换为数组,以便将此数组发送到“calculateAverageScore” 代码从数组中提取第一个数据,并用数组_值打印它们,但为了使用函数calculateAverageScore,我需要将数组_值转换为数组 $person1 = [ 'notes' => [1,2,3] ]; $person2 = [ 'notes' => [4,5,6] ]; $data=[$person1,$person2]; foreach (

我需要将“array_values”的结果转换为数组,以便将此数组发送到“calculateAverageScore”

代码从数组中提取第一个数据,并用数组_值打印它们,但为了使用函数calculateAverageScore,我需要将数组_值转换为数组

$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) 
您不需要调用数组_值,子数组已经被索引

$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

我们可以循环遍历每个项目,并将“分数”数组传递给平均和函数

“分数”已采用数组格式。下面的函数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'])
    );
}
或者,我们可以从原始数组创建一个新数组,使用array_列将名称和分数作为键和值。然后,我们可以通过一个带有array_map的函数来处理数组分数中的每个值:

输出:

Jim's average score is 2.
Derek's average score is 5.
Array
(
    [Jim] => 2
    [Derek] => 5
)

array_values返回一个数组,但当您使用array_values$student['notes'][0]时,-末尾的[0]提取数组的第一个元素。请澄清您的问题。请返回并解决您的问题。@Laurens临时变量是将前两个值存储在一起所必需的。将值单独发送到自定义函数将不起作用。由于您的回答,我已将其删除。它有值。我没有生气。@Laurens^和第二个平均值函数不应该考虑需要0-1索引values@mickmackusa我不认为他想要一个平均值,他想要每个学生的平均值2,5是两个值,2是人均$1,5是人均$2我们可以解决这个问题。[穿上队长投票中立者超级英雄斗篷]
Array
(
    [Jim] => 2
    [Derek] => 5
)