向数组添加额外的值

时间:2019-09-24 11:14:12

标签: php arrays iteration

我有以下代码

   $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数组中。我怎样才能做到这一点 ?

1 个答案:

答案 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
}