Skip to content
Advertisement

How to Rearrange an mutlidimensional array in a custom order

I’am trying to rearrange an mutlidimensional array in a to a custom order. I’am matching the keys and if these key are present in an other array it should move to the top. I couldn’t find any thing on the web nor any php functions that can do this.

$original = [
    1=>[
        1=>['brand'=> 'bmw' , 'color'=> 'white'],
        171=>['brand'=> 'audi' , 'color'=> 'black'],
        172=>['brand'=> 'volvo' , 'color'=> 'black'],
        175=>['brand'=> 'citroen' , 'color'=> 'green']
    ],
    129=>[
        201=>['brand'=> 'volkswagen' , 'color'=> 'grey'],
        206=>['brand'=> 'bentley' , 'color'=> 'grey'],
        209=>['brand'=> 'mazda' , 'color'=> 'blue'],
    ],
];

$filterOnArray = [172,175,209];

$result = [
    1=>[
        172=>['brand'=> 'volvo' , 'color'=> 'black'],//changed
        175=>['brand'=> 'citroen' , 'color'=> 'green'],//changed
        1=>['brand'=> 'bmw' , 'color'=> 'white'],       
        171=>['brand'=> 'audi' , 'color'=> 'black'],
       
    ],
    129=>[
        209=>['brand'=> 'mazda' , 'color'=> 'blue'],//changed
        201=>['brand'=> 'volkswagen' , 'color'=> 'grey'],
        206=>['brand'=> 'bentley' , 'color'=> 'grey']
    ],
];

Some code that I already have tried

        $sortedArray = [];//the main data
        $choosenFilters = [3,66,989];
        $newStackFilters = [];
        $unshiftArray = [];
        foreach ($sortedArray as $k => $v) {
            if (in_array($k, $choosenFilters)) {

                $sortedArray[$k] = $v;
                unset($sortedArray[$k]);
            } else {
                $newStackFilters[$k] = $v;
            }
        }
        $sortedArray = $unshiftArray + $newStackFilters;

Advertisement

Answer

You can use foreach() loop to do so:

$finalArray = [];


    foreach($original as $key=>$orig ){
        $nonfiter =$orig; 
        foreach($filterOnArray as $filterOnArr){
            if(isset($orig[$filterOnArr])){
                $finalArray[$key][$filterOnArr] = $orig[$filterOnArr];
                unset($nonfiter[$filterOnArr]);
            }
        }
        $finalArray[$key] = $finalArray[$key] +$nonfiter;
    }
    
    print_r($finalArray);

https://3v4l.org/BmZmj

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