phparrayssortingmultidimensional-arrayarray-multisort

Sort all rows of a 2d array to align with the sorted result of a specific row


$arr = [
    'content_type' => ['story', 'delhi', 'tez'],
    'type' => ['video_id', 'subcategory', 'story_id'],
    'fetch_id' => [32, 32, 2],
    'order' => [6, 4, 5],
    'label' => ['dsfs fdsf dsf sdf', 'dfsdfs', 'sdfsdfsd'],
    'link' => ['fsd fsdf sdf', 'fsdfsdfdsf', 'fsdfdsfds'],
    'record' => [10, 8, 12]
];

Above is the array I have to sort this array in the basis of order field and it should also sort all other fields accordingly like below example.

$arr['order'][0] = 4;
$arr['order'][1] = 5;
$arr['order'][2] = 6;

$arr['type'][0] = 'subcategory';
$arr['type'][1] = 'story_id';
$arr['type'][2] = 'video_id';

and so on.....


Solution

  • You can try this -

    $new = array();
    // Extract and get the keys as values
    $order = array_flip($array['order']);
    // sort them according to keys
    ksort($order);
    // loop through main array
    foreach($array as $key => $sub_array) {
      // loop through order
      foreach ($order as $o) {
        // store the new value according to order
        $new[$key][] = $sub_array[$o];
      }
    }
    

    Demo