1

I'm iterating over an array of courses, which all contain category IDs in the form of strings. I'm trying ro group them all by category using a matrix, but I'm having trouble doing that.

Here's an example of what I want:

$courses_by_code = [[2/11]=>[course1],[course2]], [[3/12]=>[course3], [course4]]

So my questions are:

How do I add an element that has a key that's already in the matrix to the array that corresponds to that key?

How do I create a new line in the matrix in case I find a new key?

1
  • 2
    You mean like $courses_by_code['2/11'][] = 'course5'; ? Commented May 7, 2015 at 14:21

2 Answers 2

3

I am not sure I understood 100%, but from what I understood you should do something like:

$keyThatMightExist // '2/11' for example
if(isset($courses_by_code[$keyThatMightExist])) {
    $courses_by_code[$keyThatMightExist][] = $newCourseToAdd;
} else {
    $courses_by_code[$keyThatMightExist] = array($newCourseToAdd);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Let's start with PHP's Arrays documentation:

An array in PHP is actually an ordered map. A map is a type that associates values to keys.

Something that will be invaluable to you when working with arrays is the print_r function. var_dump is also useful. You will be able to see array structure as its stored in PHP. Here's some useful things to know with arrays.

Let's answer some questions now:

How do I add an element that has a key that's already in the matrix to the array that corresponds to that key? How do I create a new line in the matrix in case I find a new key?

$courses = []; // initialize
$courses['2/11'][] = 'course1';
$courses['2/11'][] = 'course2';
$courses['3/12'][] = 'course3';
$courses['3/12'][] = 'course4';

The empty [] you see indicates that I'm adding more elements to the key 2/11. If I wanted I could also name those keys, but I'm not going to do that. Using print_r (described above) I will now print the array out in a human-readable format. Note that with print_r you generally want to surround the output with <pre> tags, as such:

echo "<pre>";
print_r($courses);
echo "</pre>";

And here is my output:

Array
(
    [2/11] => Array
        (
            [0] => course1
            [1] => course2
        )

    [3/12] => Array
        (
            [0] => course3
            [1] => course4
        )

)

Here is how I can access these elements:

echo $courses['2/11'][1]; // this is course2
echo "<br>";
print_r($courses['3/12']);    // this is the entire '3/12' array

Result:

course2
Array
(
    [0] => course3
    [1] => course4
)

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.