Было немного сложно использовать foreach с ключами.Наконец, разработали следующий код, и он работал отлично:
foreach ($question_data as $key => $question) {
foreach ($option_data as $key2 => $opt) {
if ($question_data[$key]->question_id == $option_data[$key2]['question_id'] && $question->q_type != 3) {
$question->options[] = [
'question_id' => $option_data[$key2]['question_id'],
'option_id' => $option_data[$key2]['id'],
'option_title' => $option_data[$key2]['option_title']
];
} else if($question->q_type == 3) {
$question->options = [];
}
}
}
И он обеспечил следующий результат:
"question_data": [
{
"question_id": 2,
"title": "Describe about visit",
"q_type": 3,
"question_group_id": 1,
"options": []
},
{
"question_id": 3,
"title": "How to upload data",
"q_type": 2,
"question_group_id": 1,
"options": [
{
"question_id": 3,
"option_id": 4,
"option_title": "By any device"
},
{
"question_id": 3,
"option_id": 5,
"option_title": "By mobile"
},
{
"question_id": 3,
"option_id": 6,
"option_title": "By camera"
},
{
"question_id": 3,
"option_id": 7,
"option_title": "By Laptop"
},
{
"question_id": 3,
"option_id": 8,
"option_title": "No answer"
}
]
},
{
"question_id": 4,
"title": "How to add question?",
"q_type": 3,
"question_group_id": 1,
"options": []
},
{
"question_id": 5,
"title": "Multi selection is working?",
"q_type": 1,
"question_group_id": 1,
"options": [
{
"question_id": 5,
"option_id": 9,
"option_title": "Yes"
},
{
"question_id": 5,
"option_id": 10,
"option_title": "No"
},
{
"question_id": 5,
"option_id": 11,
"option_title": "Not Confirmed"
},
{
"question_id": 5,
"option_id": 12,
"option_title": "In progress"
},
{
"question_id": 5,
"option_id": 13,
"option_title": "Testing"
}
]
}
]