Skip to content
Advertisement

Sort big array based by matching small array in php

I have an array-

$arraydelivered =
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => pending
            [2] => January
        )

    [1] => Array
        (
            [0] => 4
            [1] => pending
            [2] => April
        )

    [2] => Array
        (
            [0] => 7
            [1] => pending
            [2] => July
        )

    [3] => Array
        (
            [0] => 10
            [1] => pending
            [2] => October
        )

)

I want to resort this array dynamically to

Array
(
    

    [0] => Array
        (
            [0] => 4
            [1] => pending
            [2] => April
        )

    [1] => Array
        (
            [0] => 7
            [1] => pending
            [2] => July
        )

    [2] => Array
        (
            [0] => 10
            [1] => pending
            [2] => October
        )
[3] => Array
        (
            [0] => 1
            [1] => pending
            [2] => January
        )
)

I have tried to find out the subarray based on which I know exactly from where to re-sort

foreach ($arraydelivered as $keyD => $valueD) {
                                        if($valueD[0] == $cycle){
                                            print_r($valueD);                                    
                                        }    
                                    }

This has given me the output –

Array ( [0] => 4 [1] => pending [2] => April )

Now I want to use this sub-array as the identifier to resort to the main array. Basically this sub-array will be the resort starting point for the big array.

Advertisement

Answer

Here is the solve array

$keyD1=0;
if(!empty($arraydelivered)){
     foreach ($arraydelivered as $keyD => $valueD) {
             if($valueD[0] == $cycle){
                 $keyD1= $keyD;
               }    

       }
    $outputsec = array_slice($arraydelivered, $keyD1);
    $outputfirst = array_slice($arraydelivered, -4, $keyD1);
    $finalarray= array_merge($outputsec,$outputfirst);
    $arraydelivered=$finalarray;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement