I've got a record set from MySQL which returns the categories IDs and their values for the given objects. For example:
+-----------+-------------+----------------+
| object_id | category_id | category_value |
+-----------+-------------+----------------+
| 1 | 2 | VEGETARIAN |
| 1 | 3 | MATARÓ |
| 1 | 5 | MARCO POLO |
| 1 | 5 | JOHN DOE |
| 2 | 2 | VEGETARIAN |
| 2 | 3 | MATARÓ |
| 2 | 5 | JOHN DOE |
+-----------+-------------+----------------+
Having this, what I'd need would be the following resulting associative array in PHP:
// They are arrays, so more than one object_id can be in the same category tree (and the object_id can be repeated across categories)
$final_array['VEGETARIAN']['MATARÓ']['MARCO POLO'] = array(1);
$final_array['VEGETARIAN']['MATARÓ']['JOHN DOE'] = array(1, 2);
The query orders the results first by object_id
and, then, by category_id
with a user set order. So, it would be like ORDER BY object_id ASC, FIELD(category_id, usercat1, usercat2, usercat3)
(which in this case would be FIELD(category_id, 2, 3, 5)
.
I've got the loop which goes by every set, and I'm trying to keep a temporary variable to store the array levels, because they can change (not always will be 3 levels), so something like:
$temporary_array['VEGETARIAN'] = array();
$temporary_array = $temporary_array['VEGETARIAN'];
// And then, on the next iteration
$temporary_array['MATARÓ'] = array();
$temporary_array = $temporary_array['MATARÓ'];
// Now, $temporary_array would be equal to $temporary_array['VEGETARIAN']['MATARÓ'];
So I can create a main key based on the new category value which will be stored as a child of the parent array, and get all the hierarchical tree. Each level should include all the next ones.
I've tried to declare it globally and pass it by reference but it seems not to work.
Is there any way to achieve this in PHP? How would you make to get the desired result?
EDIT:
I've been more close to get it reversing the order of the categories, so I get first the last category (the one that has no other categories inside it) and I go upwards the array, something like this:
// Long story very short, would be like
$final_array['new_category_value'] = $old_final_array;
And keep going up for every object. When I change the object_id
, then I make:
array_merge_recursive($final_array, $actual_object_array);
However, I'm still not able to get the desired result.
Thank you for your time and comments!