我的数据库中有一个已提取和反序列化的序列化数组。它有这样的结构:
array (
526744 =>
array (
'completed' => 13,
'total' => 24,
'topics' =>
array (
),
'lessons' =>
array (
526745 => 1,
526747 => 1,
526749 => 1,
526751 => 0,
526753 => 0,
526755 => 0,
526757 => 0,
526759 => 0,
526761 => 1,
),
'last_id' => 526793,
)
第一个数字是一个课程ID(实际上有3个课程,我刚刚包括第一个课程)。
我已经将其从数据库中删除了几个不同的用户,所以我已经多次完成了这些。
我正在尝试计算课程,以便我知道有多少用户通过了每节课。
我有以下代码:
foreach($results as $result) {
$course_progress = unserialize($result->course_progress);
$lesson_progress = $course_progress[$course_id][lessons];
print_r(array_count_values($lesson_progress));
}
这输出:
Array ( [1] => 24 )
Array ( [1] => 11 [0] => 13 )
Array ( [1] => 13 [0] => 11 )
Array ( [1] => 24 )
Array ( [1] => 24 )
Array ( [1] => 24 )
Array ( [1] => 24 )
Array ( [1] => 23 [0] => 1 )
Array ( [1] => 24 )
Array ( [1] => 21 [0] => 3 )
Array ( [1] => 24 )
Array ( [1] => 24 )
Array ( [1] => 24 )
Array ( [1] => 24 )
Array ( [0] => 21 [1] => 3 )
这显然是完全错误的。但我想不出如何让它发挥作用。我认为问题是我的每个用户都有一个单独的数组,我的当前代码可能是吗?
非常感谢任何帮助。
答案 0 :(得分:1)
尝试4:
$users = array(
'john' => array(
526744 => array (
'completed' => 13,
'total' => 24,
'topics' =>
array (),
'lessons' =>
array (
526745 => 1,
526747 => 1,
526749 => 1,
526751 => 0,
526753 => 0,
526755 => 0,
526757 => 0,
526759 => 0,
526761 => 1,
),
'last_id' => 526793,
),
526745 => array (
'completed' => 13,
'total' => 24,
'topics' =>
array (),
'lessons' =>
array (
526745 => 1,
526747 => 1,
526749 => 1,
526751 => 0,
526753 => 1,
526755 => 0,
526757 => 0,
526759 => 0,
526761 => 1,
),
'last_id' => 526793,
),
),
'joe' => array(
526744 => array (
'completed' => 13,
'total' => 24,
'topics' =>
array (),
'lessons' =>
array (
526745 => 1,
526747 => 1,
526749 => 1,
526751 => 0,
526753 => 0,
526755 => 0,
526757 => 0,
526759 => 0,
526761 => 1,
),
'last_id' => 526793,
),
526745 => array (
'completed' => 13,
'total' => 24,
'topics' =>
array (),
'lessons' =>
array (
526745 => 1,
526747 => 1,
526749 => 1,
526751 => 1,
526753 => 1,
526755 => 0,
526757 => 0,
526759 => 0,
526761 => 1,
),
'last_id' => 526793,
),
)
);
$counts = [];
foreach($users as $userId => $userCourses){
foreach($userCourses as $courseId => $course){
foreach($course['lessons'] as $lessonId => $lesson){
$counts[$courseId][$lessonId] = empty($counts[$courseId][$lessonId]) ? $lesson : $counts[$courseId][$lessonId]+$lesson;
}
}
}
var_dump($counts);
显然我的数组键(john和joe)仅用于测试目的,因此最外层的foreach可以忽略不计。
返回:
array (size=2)
526744 =>
array (size=9)
526745 => int 2
526747 => int 2
526749 => int 2
526751 => int 0
526753 => int 0
526755 => int 0
526757 => int 0
526759 => int 0
526761 => int 2
526745 =>
array (size=9)
526745 => int 2
526747 => int 2
526749 => int 2
526751 => int 1
526753 => int 2
526755 => int 0
526757 => int 0
526759 => int 0
526761 => int 2