我在循环中打印此数组的结果时遇到问题(要显示在前端)。能够获得章节名称(例如,Chapter_Name_Unique),章节名称的总章节后视图计数,以及该章节名称(或组)中每个chapter_member的全名的目标。我认为这里没有正确的结构,因为我有问题在循环。
我的逻辑关闭了吗?
print_r
看起来像这样:
Array
(
[Chapter_Name_Unique] => Array
(
[chapter_post_views_count] => 3338
[chapter_members] => Array
(
[0] => Array
(
[post_views_count] => 3338
[first_name] => Mary
[last_name] => Jane
[fullname] => maryjane
[chapter_name] => Chapter_Name_Unique
)
)
)
[Chapter_Name_Unique_2] => Array
(
[chapter_post_views_count] => 783
[chapter_members] => Array
(
[0] => Array
(
[post_views_count] => 404
[first_name] => Betty
[last_name] => Lou
[fullname] => bettylou
[chapter_name] => Chapter_Name_Unique_2
)
[1] => Array
(
[post_views_count] => 379
[first_name] => Judy
[last_name] => Jones
[fullname] => judyjones
[chapter_name] => Chapter_Name_Unique_2
)
)
)
)
,实际功能如下:
$grouped_types = array();
// to add together post counts of group members
foreach($users as $chapter){
$grouped_types[$chapter['chapter_name']]['chapter_post_views_count'] += $chapter['post_views_count'];
}
// to group on top level by chapter_name
foreach($users as $chapter){
$grouped_types[$chapter['chapter_name']]['chapter_members'][] = $chapter;
}
echo "<pre>";
print_r( $grouped_types );
echo "</pre>";
答案 0 :(得分:1)
尝试类似的事情(假设$users
中的print_r()
是您的数组)
$grouped_types = array();
foreach($users as $chapter=>$data){
$grouped_types[$chapter]['chapter_post_views_count'] = $data['chapter_post_views_count'];
foreach($data['chapter_members'] as $member){
$grouped_types[$chapter]['chapter_members'][] = $members['fullname'];
}
}
echo "<pre>";
print_r( $grouped_types );
echo "</pre>";
答案 1 :(得分:-1)
非常感谢你们,你们的提示确实很有帮助。我两个人都用了一点,然后把它拉到一起:
foreach( $grouped_types as $chapter_name_unique => $vars) {
$chapter_post_views = $vars['chapter_post_views_count'];
$chapter_members = $vars['chapter_members'];
echo $chapter_name_unique; // echo chapter name (level 1)
echo $chapter_post_views; // echo chapter post views (level 2 - $vars before)
foreach( $vars['chapter_members'] as $member){ // loop through all chapter_members
$vars['chapter_members'][] = $member['fullname'];
echo $member['fullname']; // echo all usernames within the group
}
}
结合上面的另外两个foreach语句(它们一起使用并保存到$grouped_types
数组中),这完全符合我的需要。 (希望没有太多不必要的循环?)
再次感谢!