amit singh amit singh - 22 days ago 7
PHP Question

Sorting php array by column in ascending order

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.....

Answer

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

Comments