Roeland
Roeland

Reputation: 3858

Order an array with arrays inside of it by the first arrays keys

So lets say I have an array that I want to organize by the keys. I thought I would just use ksort, but that does not work on the array below. Essentially I want to organize it so it would be A,R,Z. if I do ksort on this array it just returns 1.

array
( 
  [Z] => array
     (
        [dked] => asddadff
        [fettyda] => dfdf
        [feqed] => aasdf 
      )
  [A] => array
     (
        [fdkded] => asddadff
        [athgda] => dfdf
      )

  [R] => array
     (
        [fadfded] => asddadff
        [adfthgda] => dfdf
        [gadfhd] => aasdf 
        [gadfhd] => aasdf 
      )
)

Upvotes: 0

Views: 56

Answers (3)

Anush Prem
Anush Prem

Reputation: 1481

if you are getting 1 as response, then you might be trying this

$array = ksort($array);

But ksort's return value is true or false, not the sorted array.

ksort($array);
print_r ($array);

This is enough. ksort receives the parameter as a reference, so you don't want to assign it back.

Read more here. ksort

Upvotes: 1

Jonathan M
Jonathan M

Reputation: 17451

Your array declaration needs strings for the indices and values. Also notice the use of commas:

array
( 
  "Z" => array
     (
        "dked" => "asddadff", 
        "fettyda" => "dfdf",
        "feqed" => "aasdf",
      ),
  "A" => array
     (
        "fdkded" => "asddadff",
        "athgda" => "dfdf",
      ),

  "R" => array
     (
        "fadfded" => "asddadff",
        "adfthgda" => "dfdf",
        "gadfhd" => "aasdf",
        "gadfhd" => "aasdf",
      )
)

Use ksort with the above array.

Here's a good reference on array literal notation in PHP: http://php.net/manual/en/language.types.array.php

Upvotes: 0

Punit
Punit

Reputation: 1120

sample working code:

<?php
$var = array('Z'=>array('dked'=>'asddadff','fettyda'=>'dfdf'),'A'=>array('fdkded'=>'asddadff','athgda'=>'dfdf'),'R'=>array('fadfded'=>'asddadff','adfthgda'=>'dfdf'));
ksort($var);
print_r($var);
?>

Upvotes: 1

Related Questions