我能够使用foreach
通过公共密钥对数组进行分组现在我希望进一步创建一个以逗号分隔的列表,每次尝试都会产生一个列表,但没有逗号;他们要么被删除,要么我没有这样做。
$families = array();
foreach($results as $key => $item) {
$families[$item['family_id']][] = $item;
}
Array (
[54] => Array (
[0] => Array (
[family_id] => 54
[firstname] => Adam
[primary] => 1
)
)
[89] => Array (
[0] => Array (
[family_id] => 89
[firstname] => Alex
[primary] => 1
)
)
[44] => Array (
[0] => Array (
[family_id] => 44
[firstname] => Anne-Marie
[primary] => 1
)
)
[282] => Array (
[0] => Array (
[family_id] => 282
[firstname] => Ashley
[primary] => 1
)
[1] => Array (
[family_id] => 282
[firstname] => Leah
[primary] =>
)
[2] => Array (
[family_id] => 282
[firstname] => Brad
[primary] =>
)
)
[292] => Array (
[0] => Array (
[family_id] => 292
[firstname] => Brenda
[primary] => 1
)
)
)
最终结果是foreach
生成以下有子女的家庭列表。
家庭:亚当
家庭:亚历克斯
家庭:安妮玛丽
家庭:Ashley
孩子们:Leah,Brad
家庭:布伦达
foreach($families as $family) {
foreach($family as $key => $value) {
if (empty($value['primary'])) {
$children = array('firstname' => $value['firstname']);
$child = implode(', ', $children);
}
if (!empty($value['primary'])) {
echo 'Family: '.$value['firstname'];
}
}
}
答案 0 :(得分:0)
你可以尝试先将父母,然后是孩子,分成不同的数组
user: Ember.inject.controller()
array_filter帮助我们排除非想要的数据,而array_map允许我们在每个数组元素上执行一个函数:例如返回firstname。