1

I have a database table with two fields, subject_id, and teacher_id. In the subject_id field are numbers representing subjects like math, science, english. The teacher_id fields represents various teachers. Their presence together on the same row means that teacher 1 teaches subject 2, or on a different row, teacher 1 teaches subject 5, or on a different row teacher 4 teaches subject 2, etc... It is a many-to-many relationship.

After querying from the database, I get an array of this structure:

Array
(
[0] => Array
    (
        [first_name] => bob
        [subject_en_name] => italian
    )

[1] => Array
    (
        [first_name] => bob
        [subject_en_name] => japanese
    )

[2] => Array
    (
        [first_name] => bob
        [subject_en_name] => korean
    )

[3] => Array
    (
        [first_name] => sally
        [subject_en_name] => math
    )

[4] => Array
    (
        [first_name] => sally
        [subject_en_name] => GMAT
    )

)

I need to screen for the first name, and print out a sentence like:

Bob teaches italian, japanese, korean...
Sally teaches math, GMAT...

Using a foreach construction

foreach ($teacher_object as $t_object)
{
    echo $t_object['first_name'] . " teaches " . $t_object['subject_en_name'] . "<br>";

}

I've only been able to manage these printouts:

bob teaches italian
bob teaches japanese
bob teaches korean
sally teaches math
sally teaches GMAT

Is there a php function for sorting array that can help me? Some other solution?

1 Answer 1

4

Rearrange your array first, so that you have a new array with the teacher names as the index, and classes as a sub-array:

$teaches = array();
foreach ($teacher_object as $t_object) {
    $teaches[$t_object['first_name']][] = $t_object['subject_en_name'];
}

The new array will look like this:

Array
(
    [bob] => Array
        (
            [0] => italian
            [1] => japanese
            [2] => korean
        )

    [sally] => Array
        (
            [0] => math
            [1] => GMAT
        )

)

Now you have a much easier array to loop through. Something like this:

foreach($teaches AS $teacher => $classes) {
    echo $teacher . " teaches " . implode(", ",$classes) . "<br/>";
}

Gives you...

bob teaches italian, japanese, korean
sally teaches math, GMAT
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.