I need some help because I'm stuck. I've developed a HTML/JS/PHP sorting where users can move elements around or create child elements by moving an element inside another. As a result, I'm getting this array:
$sorted_ids = [
'2', // <-- Value = Main element ID
[
'4' => [ // <-- Key = Main element ID
'3' // <-- Value = Child element ID
]
]
'1', // <-- Value = Main element ID
];
On the other side, I have my array of elements containing all of these above IDs:
$elements = [
[
'id' => '1',
'name' => 'Test1'
],
[
'id' => '2',
'name' => 'Test2'
],
[
'id' => '3',
'name' => 'Test3'
],
[
'id' => '4',
'name' => 'Test4'
]
];
I've used now the following code to loop through the array of sorted IDs:
foreach ( $sorted_ids as $sorted_id ) {
if ( is_array( $sorted_id ) ) {
foreach ( $sorted_id as $sorted_parent_id => $sorted_child_id ) {
}
} else {
}
}
In my loop, I can now access all relevant IDs, but I really don't know how to sort the elements by its field ID. I've tried using array_shift()
but always went wrong. Maybe there is a better idea?
At the end, my elements array need to look like this:
$elements = [
[
'id' => '2'
'name' => 'Test2'
],
[
'id' => '4',
'name' => 'Test4'
],
[
'id' => '3',
'name' => 'Test3'
],
[
'id' => '1,
'name' => 'Test1'
]
];
Update
I forgot to mention that my objects in the elements array can have multiple fields like name, field, place, value...
(I just added name as an example), so just flatten the sorted IDs array might be a good idea, but problematic!