2

I need one help.I need to sort array as per its index value using PHP. I am explaining my code below.

Array ( [0] => Array ( [id] => 17 [name] => Exhibition ) [2] => Array ( [id] => 16 [name] => Office Space ) [3] => Array ( [id] => 15 [name] => Storage ) [1] => Array ( [id] => 14 [name] => Parking ) )

Here this arrays order is different like 0,2,3,1. I need its index like 0,1,2,3. Please help me.

2 Answers2

2

ksort() is the answer you need.

masterFly
  • 1,047
  • 8
  • 20
2

use ksort(), which sorts an array by its keys.

So I created this dummy $test array example:

array(4) { 
    [0]=> array(2) { ["id"]=> int(1) ["name"]=> string(3) "one" } 
    [3]=> array(2) { ["id"]=> int(4) ["name"]=> string(4) "four" } 
    [1]=> array(2) { ["id"]=> int(2) ["name"]=> string(3) "two" } 
    [2]=> array(2) { ["id"]=> int(3) ["name"]=> string(5) "three" } 
} 

next ksort() Sorts an array by key, maintaining key to data correlations.

ksort($test);

Now var_dump gives output

array(4) { 
    [0]=> array(2) { ["id"]=> int(1) ["name"]=> string(3) "one" } 
    [1]=> array(2) { ["id"]=> int(2) ["name"]=> string(3) "two" } 
    [2]=> array(2) { ["id"]=> int(3) ["name"]=> string(5) "three" } 
    [3]=> array(2) { ["id"]=> int(4) ["name"]=> string(4) "four" } 
} 
Sylvester
  • 389
  • 4
  • 11
  • I did like `$caArr=ksort($catArr); print_r($caArr);` but its not printing anything.here `$catArr` holds the root array which is given in my post. –  Mar 31 '17 at 07:06
  • Just use ksort($catArr); print_r($catArr); to achieve the sort then display. Your previous code will do that, and then assign the result of the sort to $caArr as either true (succcess) or false (fail), but unless you're interested in this return value you can simply igore assining it to anything. – Gavin Jackson Mar 31 '17 at 07:10
  • dummy array $test : array(4) { [0]=> array(2) { ["id"]=> int(1) ["name"]=> string(3) "one" } [3]=> array(2) { ["id"]=> int(4) ["name"]=> string(4) "four" } [1]=> array(2) { ["id"]=> int(2) ["name"]=> string(3) "two" } [2]=> array(2) { ["id"]=> int(3) ["name"]=> string(5) "three" } } ksort($test ); var_dump($test); output: array(4) { [0]=> array(2) { ["id"]=> int(1) ["name"]=> string(3) "one" } [1]=> array(2) { ["id"]=> int(2) ["name"]=> string(3) "two" } [2]=> array(2) { ["id"]=> int(3) ["name"]=> string(5) "three" } [3]=> array(2) { ["id"]=> int(4) ["name"]=> string(4) "four" } } – Sylvester Mar 31 '17 at 07:57
  • i'll edit my answer and explain more – Sylvester Mar 31 '17 at 08:00