Skip to content
Advertisement

Move element to last index of array, multidimensional

I have a simple loop on an array to produce a new array called dataBlock:

$dataBlock = [];

    foreach($root as $data){
        if (array_key_exists($this->number, $root)) {
            $dataBlock = $root[$this->number];
        }
    } 

dd($dataBlock);

The dump produces this:

array:[
    "abc"=>array:[]
    "total"=>array:[]
    "def"=>array:[]
]

But I want total at the bottom like this:

array:[
    "abc"=>array:[]
    "def"=>array:[]
    "total"=>array:[]
]

How can I properly move the ‘total’ element to the last index of the array?

Advertisement

Answer

The simplest way to achieve this is to copy the total element, unset it, and then add it back again, which will automatically add it to the end of the array:

$data = array(
    'abc' => array(4, 5, 6),
    'total' => array(7, 8, 9),
    'def' => array(3, 4, 5)
    );
    
$total = $data['total'];
unset($data['total']);
$data['total'] = $total;
print_r($data);

Output:

Array
(
    [abc] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )
    [def] => Array
        (
            [0] => 3
            [1] => 4
            [2] => 5
        )
    [total] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 9
        )
)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement