将数组值转换为数组

时间:2019-01-16 16:06:17

标签: php arrays

我需要将'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) 

2 个答案:

答案 0 :(得分:0)

我们可以遍历每一项并将“分数”数组传递给平均求和函数。

'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
)

答案 1 :(得分:-1)

您无需调用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