2 回答

TA貢獻1805條經驗 獲得超10個贊
您可以在array_walk()的幫助下嘗試以下方法。
$classType = [
["class" => "1", "type" => "A"],
["class" => "2", "type" => "A"],
["class" => "3", "type" => "B"]
];
$clollege['studentDetails'] = [
["grade" => "2", "hobbies" => ["A" , "B"] ],
["grade" => "2", "hobbies" => ["A" ] ],
["grade" => "3", "hobbies" => [ "C" ] ]
];
$classType = array_column($classType, 'type', "class");
array_walk($clollege['studentDetails'], function(&$item) use($classType) {
$item['type'] = $classType[$item['grade']];
});
echo '<pre>';
print_r($clollege['studentDetails']);
echo '</pre>';

TA貢獻1856條經驗 獲得超11個贊
您不能grade在單個或子數組元素中用作鍵 2 次,我已經通過使用type索引提到了解決方案。
你可以用foreach與array_reduce
foreach($clollege['studentDetails'] as $key => &$val){
$grade = $val['grade'];
$val['type'] = array_reduce($classType, function($r, $item) use ($grade){
return ($item['class'] == $grade) ? $item['type'] : $r;
});
}
print_r($clollege);
更新
更改代碼
$grade = $val['grade'];
到
$grade = $val['group']['grade'];
如果有機會為這兩種情況使用
$grade = isset($val['group']['grade']) ? $val['group']['grade'] : $val['grade'];
工作演示:https : //3v4l.org/5HGLk
- 2 回答
- 0 關注
- 161 瀏覽
添加回答
舉報