To begin with I have an array (courses) like this:
array(2)
{
[0] => array(2)
{
["title"] => string "course1"
["code"] => string "001, 002, 003"
}
[1] => array(2)
{
["title"] => string "course2"
["ps_course_code"] => string "004"
}
}
Sometimes the 'code' will contain multiple codes as a comma separated string, other times 'code' will contain a single code.
To get individual codes I loop through the courses array and use explode to separate out the codes:
foreach($courses as $course) {
$courseInfo['code'] = explode(",",$course["code"]);
$courseInfo['title'] = $course["title"];
var_dump($courseInfo);
}
This gives me a new array for each course:
array(2)
{
["code"] => array(3)
{
[0] => string "001",
[1] => string "002",
[2] => string "003",
}
["title"] => string "course1"
}
array(2)
{
["code"] => array(1)
{
[0] => string "004"
}
["title"] => string "course2"
}
What I need though is a new array that contains every code and its title. So for some courses this means there will be multiple codes with the same title. E.g:
array(4)
{
[0] => array (2)
{
["code"] => string "001",
["title"] => string "course1"
}
[1] => array (2)
{
["code"] => string "002",
["title"] => string "course1"
}
[2] => array (2)
{
["code"] => string "003",
["title"] => string "course1"
}
[3] => array (2)
{
["code"] => string "004",
["title"] => string "course1"
}
}
I'm really struggling with this. Do I need another loop inside the first in order to create the final array?
foreach($courses as $course) {
$courseInfo['code'] = explode(",",$course["code"]);
$courseInfo['title'] = $course["title"];
// Another loop to create final array?
foreach($courseInfo as $value) {
$final['code'] = $value['code']; // I know this doesn't work!
$final['title'] = $value['title'];
}
}
var_dump($final);
I know this is long and I probably haven't explained this very well, so apologies!
array(code => title, code2 => title2, …)?