Q . Sorting php array by column in ascending order.

Brad Johnson. asked, Nov 11 ' 2016
Array
(
    [content_type] => Array
        (
            [0] => story
            [1] => delhi
            [2] => tez
        )

    [type] => Array
        (
            [0] => video_id
            [1] => subcategory
            [2] => story_id
        )

    [fetch_id] => Array
        (
            [0] => 32
            [1] => 32
            [2] => 2
        )

    [order] => Array
        (
            [0] => 6
            [1] => 4
            [2] => 5
        )

    [label] => Array
        (
            [0] => dsfs fdsf dsf sdf 
            [1] => dfsdfs
            [2] => sdfsdfsd
        )

    [link] => Array
        (
            [0] => fsd fsdf sdf
            [1] => fsdfsdfdsf
            [2] => fsdfdsfds
        )

    [record] => Array
        (
            [0] => 10
            [1] => 8
            [2] => 12
        )

)

Above is the array I have to sort this array in the basis of order field and it should shorted all the 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.....

 

  • PHP
  • arrays
  • sorting
  • multidimensional-array

2 Answers

You can try this -

<?php
$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];
  }
}

 

Some lesser solution:

<?php

asort($array['order']);
foreach ($array as $key => $subArray) {
    $array[$key] = array_replace($array['order'], $subArray);
}

For reset a key sequence you may just to use array_values().

Leave a Ansewer