I've been struggling for a while now. I have 2 arrays that I want to compare with each other. A user array and a lesson array. The Keys in the lesson array are the ID's of that lesson
Lesson Array:
Array(
// The key in this array ([143] or [13]) is the lesson ID each lesson contains one ore more topics
[143] => Array (
[0] => 315 // example: 315 is a topic ID within lesson 143
[1] => 311
[2] => 176
[3] => 145
)
[13] => Array (
[0] => 27
[1] => 25
)
)
The user array contains only the information about which topics that user has completed. Topic with lesson ID's that are not completed don't exist in this array.
Main question: I want to compare the topic ID's of the user array to the Lesson array. And I want to put the topics that aren't completed in a seperate array.
User array
Array (
[0] => Array (
[143] => Array (
[145] => 1 // (this 1 means it is completed, this key is a topic ID)
[176] => 1
)
)
[1] => Array (
[13] => Array (
[25] => 1
)
)
)
In this example above the result i want to get is an array with non matching id's like:
$result = array( 143 => array(311,315), 13 => array(27))
I hope it's a little bit clear.
If anyone can point me out in the right direction I'll be very glad! I tried a lot of things but to post them all here it's not clarifying the main question.
you have to use array_keys
and array_diff
. Online compile at My answer
Arrays
$lesson = array(
"143" => array("315", "311", "176", "145"),
"13" => array("27", "25")
);
$user = array(
array("143" => array("145" => "1", "176" => "1")),
array("13" => array("25" => "1"))
);
Mechanism/ process
$result = array();
foreach ($user as $key => $value) {
foreach ($value as $key2 => $value2) {
$result[$key2] = array_diff($lesson[$key2], array_keys($value2));
}
}
Result
echo '<pre>';
print_r($result);
echo '</pre>';
Output
Array
(
[143] => Array
(
[0] => 315
[1] => 311
)
[13] => Array
(
[0] => 27
)
)
The first thing I'd do is modify the User array using probably array_flip() so that I'd end up with something like this:
Array (
[0] => Array (
[143] => Array (
[0] => 145
[1] => 176
)
)
[1] => Array (
[13] => Array (
[0] => 25
)
)
Once that's done, all you have to do is use the array_diff() function to compare the two arrays and you'll have whatever element is only in the first array:
$diff = array_diff($lesson[143], $user[0][143])
I hope this helps.