我有以下代码
$result = array();
$category_name = array();
foreach($category as $cat) {
$category_name[] = $cat->category_name; // I would like to add this value to result array
$campaigns = $cat->users()->orderBy('id','desc')->paginate(20);
foreach($campaigns as $campaign) {
$result[] = $campaign;
}
}
在执行$result
循环时,我想将此值($ cat-> category_name;)添加到foreach
数组中。我怎样才能做到这一点 ?
答案 0 :(得分:1)
我认为您的意思是:
$result = array();
$category_name = array();
foreach($category as $cat) {
$category_name[] = $cat->category_name;
$result2 = array();
$result2[] = $cat->category_name;
$campaigns = $cat->users()->orderBy('id','desc')->paginate(20);
foreach($campaigns as $campaign) {
$result2[] = $campaign;
}
$result[] = $result2;
}
或者:
$result = array();
$category_name = array();
foreach($category as $cat) {
$category_name[] = $cat->category_name;
$result2 = array();
$campaigns = $cat->users()->orderBy('id','desc')->paginate(20);
foreach($campaigns as $campaign) {
$result2[] = $campaign;
}
$result[$cat->category_name] = $result2;
}
然后对于第二个示例,您可以执行以下操作:
foreach ($result as $category_name => $campaigns) {
... // $campaigns is a list here
}