Question

i have an issue i need to fix sooner than later. if i had the time to rewrite the entire script i would, but such is the life of a programmer, right? anywho, i've taken over a project and i have a multidimensional mixed associative/numeric array like so:

Array
(
    [item1] => Array
        (
            [dataset] => Array()
            [3] => Array()
            [7] => Array()
        )
    [item2] => Array
        (
            [dataset] => Array()
            [4] => Array()
            [19] => Array()
            [2] => Array()
        )
)

what i need to do is shift the dataset index in each of the itemX indexes to be the last index to result this:

Array
(
    [item1] => Array
        (
            [3] => Array()
            [7] => Array()
            [dataset] => Array()
        )
    [item2] => Array
        (
            [4] => Array()
            [19] => Array()
            [2] => Array()
            [dataset] => Array()
        )
)

a few things that may help make this happen is that i know that the dataset index will always be the first index in the itemX index and the key will always be 'dataset' and the others will all always be numeric indexes. is there anyway to do this in php? the fact that it's a mixed array is throwing me. i can't have the numeric indexes getting reset and starting at 0. it doesn't matter if they're order is shifted, only that they all come before the 'dataset' index. maybe it's just one of those days.... :\ any suggestions or comments are greatly appreciated.

Was it helpful?

Solution

Loop though all elements like this:

foreach ($all_items as $key =>$items) {
   $dataset = $items['dataset'];
   unset($all_items[$key]['dataset']); // Removing it (from the top)
   $all_items[$key]['dataset'] = $dataset; // Adding it again (at the bottom)
}

Unsetting the 'dataset' element and adding it again will cause the element to be added at the bottom.

It's important that you modify the original array directly, not the $items from the foreach, because those changes will not affect the original array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top