gpt4 book ai didi

javascript - php根据条件合并数组

转载 作者:行者123 更新时间:2023-11-30 20:31:59 25 4
gpt4 key购买 nike

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

Array
(
[0] => stdClass Object
(
[chapter_name] => Algebra
[chapter_id] => 1
[module_id] => 12
)

[1] => stdClass Object
(
[chapter_name] => Combinatorics
[chapter_id] => 2
[module_id] => 12
)

[2] => stdClass Object
(
[chapter_name] => Mathematical physics
[chapter_id] => 3
[module_id] => 12
)

[3] => stdClass Object
(
[chapter_name] => Calculus and analysis
[chapter_id] => 6
[module_id] => 12
)

)

第二个数组是这样的:

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
)

)

我希望最终输出应该是 json 之类的:

[
{
moduleName: "Camp",
chapters: [

],

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

],

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

代码如下:

$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
]);
}

最佳答案

您需要像这样更改您的第二个 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

关于javascript - php根据条件合并数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50246125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com