根据php中的条件合并数组

时间:2018-05-09 05:30:50

标签: javascript php

我刚开始学习php并使用php创建项目。在我的代码中我使用php创建Web服务,需要合并数组并在数组上创建。最后一个输出应该是json。 当我打印第一个数组时,它看起来:

Array
(
    [0] => stdClass Object
        (
            [unimodule_name] => Artificial Intelligence
            [module_id] => 7
        )

    [1] => stdClass Object
        (
            [unimodule_name] => Camp
            [module_id] => 11
        )

    [2] => stdClass Object
        (
            [unimodule_name] => Mathematics
            [module_id] => 12
        )

)

第二个数组就像:

[
  {
    moduleName: "Camp",
    chapters: [

    ],

  },
  {
    moduleName: "Artificial Intelligence",
    chapters: [

    ],

  },
  {
    moduleName: "Mathematics",
    chapters: [
      {
        Chaptername: "test"
      },
      {
        Chaptername: Calculusandanalysis
      },
      {
        Chaptername: Algebra
      },
      {
        Chaptername: Combinatorics
      }
    ]
  }
]

我希望最终输出应该在json中,如:

$results = DB::select( DB::raw("select unimodules.name as unimodule_name, unimodules.id as unimodule_id from unimodules WHERE course_id = 5 AND unimodules.name IS NOT NULL"));

    print_r($results); // first array

foreach ($results as $result) {

    $chapters = [];

    $chapters = DB::select( DB::raw("select chapters.name as chapter_name, chapters.id as chapter_id, chapters.module_id from chapters WHERE module_id = ".$result->unimodule_id.""));

}
    print_r($chapters); // second array

    return response()->json([
        'data' => $results,
        'message' => 'course_success',
        'status' => 200
    ]);
}

这是代码:

heroes
|--hero-detail
|  |--hero-detail.component.ts|htmlcss|spec.ts
|--hero-list
|  |--hero-list.component.ts|html|css|spec.ts
|--shared
|  |--hero-button.component.ts|html|css|spec.ts
|  |--hero.model.ts
|  |--hero.service.ts|spec.ts
|--heroes.component.ts|html|css|spec.ts
|--heroes.module.ts
|--heroes-routing.module.ts

1 个答案:

答案 0 :(得分:1)

您需要更改第二个foreach()代码(用于获取章节),如下所示: -

$final_array = []; //define your final array what you want at end
foreach ($results as $result) {

    $final_array[$result->unimodule_name]['moduleName'] = $result->unimodule_name; // assign module name to the final array

    $chapters = DB::select( DB::raw("select chapters.name as chapter_name, chapters.id as chapter_id, chapters.module_id from chapters WHERE module_id = ".$result->unimodule_id.""));

    if(count($chapters)>0){
        foreach($chapters as $chapter){
            $final_array[$result->unimodule_name]['chapters'][] = ['Chaptername'=>$chapter->chapter_name]; //assign all chapters to corresponding module

        }
    }else{
        $final_array[$result->unimodule_name]['chapters'] = [];
    }

}

$final_array = array_values($final_array); // remove associative array key indexes

echo "<pre/>";print_r($final_array); // print to check you got desired output or not