Sorting array by keys (PHP)

Status
Not open for further replies.

wireframed

Ars Legatus Legionis
17,367
Subscriptor
I've got a little problem getting an array sorted, and I'm not sure what the best method is.

Basically I've got an array with a bunch of keys like:
Code:
array (size=12)
  0 => 
    object(stdClass)[336]
      public 'name' => string 'imdg' (length=4)
      public 'title' => string 'IMDG' (length=4)
      public 'group' => string 'group1' (length=11)
  1 => 
    object(stdClass)[337]
      public 'name' => string 'iata' (length=4)
      public 'title' => string 'IATA' (length=4)
      public 'group' => string 'group1' (length=11)
  2 => 
    object(stdClass)[338]
      public 'name' => string 'rid' (length=3)
      public 'title' => string 'RID' (length=3)
      public 'group' => string 'group2' (length=11)
  3 => 
    object(stdClass)[339]
      public 'name' => string 'reach' (length=5)
      public 'title' => string 'REACH' (length=5)
      public 'group' => string 'group2' (length=11)

What I need to do is loop this array out, but sort them by the group their in, so I can arrange them in groups in my output. I.e. I need to have all "group1" looped out, then all "group2" and so on, but I need to be able to wrap content around each group in the HTML.

The tricky part is, I can't know exactly how many different groups I have, other than I can query the database, and get an array of which groups there are. So I really need to use an array of group names to sort this array by. Otherwise I could just use some "while..." in my foreaches, I suppose.
Does that make sense?

I'm not terribly strong with arrays, so while I can think of a few ways that seem logical, I'm not really sure what the best mechanism is in code.

L.
 

wireframed

Ars Legatus Legionis
17,367
Subscriptor
[url=http:/civis/viewtopic.php?p=27970291#p27970291:ccbt5810 said:
btmlltt[/url]":ccbt5810]http://php.net/manual/en/array.sorting.php

There are several that allow you to sort by a custom method.
Yes, that's what I also got when I searched Google.

I'm trying to create a multi-dimensional array from the sort, and I'm not sure which method is best, since I've been through the methods, and none of them seem to sort a 2-dimensional array into a 3-dimensional.
So I'm looking for the best logic for structuring this, not just a google result. :-/

Might be too complex for a forum question, and if so that's ok too.

L.
 

wireframed

Ars Legatus Legionis
17,367
Subscriptor
I re-read my question, and the exact expected result isn't as clear as it could have been - sorry. I'll try again:

The array now is (condensed):
Code:
array(
   [0]=>
      somekey=>somevalue,
      somekey=>somevalue,
      group=>groupName1
   [1]=>
      somekey=>somevalue,
      somekey=>somevalue,
      group=>groupName1
   [2]=>
      somekey=>somevalue,
      somekey=>somevalue,
      group=>groupName1
   [3]=>
      somekey=>somevalue,
      somekey=>somevalue,
      group=>groupName2
   [4]=>
      somekey=>somevalue,
      somekey=>somevalue,
      group=>groupName2

);

What I want:
Code:
array(
   group=>groupName1
      [0]=>
         somekey=>somevalue,
         somekey=>somevalue
      [1]
         somekey=>somevalue,
         somekey=>somevalue
      [2]
         somekey=>somevalue,
         somekey=>somevalue
   group=>groupName2
      [0]=>
         somekey=>somevalue,
         somekey=>somevalue
      [1]=>
         somekey=>somevalue,
         somekey=>somevalue

);
(Yeah, my array code is a mess, but I hope you get the idea :p)
Basically I need to create new arrays based on the "Group" value, and sort the array by, and this is somewhat more complex than what I usually need to do with arrays.

The alternative is do to a database queries for each "GroupName", and put them in seperate arrays, but I'm assuming doing X SQL queries is more expensive on the server than doing 1 and then sorting into X arrays?

:EDIT: And lastly - while I DO know how many and which "GroupName" there are, they are user created, so I have to assume I won't. I have all the groups in a separate array, for use in a different place.

L.
 

wireframed

Ars Legatus Legionis
17,367
Subscriptor
Okay, so for now, I've ended up creating a "foreach" loop, and doing a number of queries, that I gather up in a single array, with the result of each query assigned to a key. It's unlikely to exceed 8-10 queries, each returning a dozen rows or less.

It's probably wildly inefficient on the database, but I'm kinda out of time on this one. :) It's not likely they'll see a lot of stress on this site, but if someone offers up a better solution, or hints for one, I might go back and rework it to be more optimal.

L.
 

Marco

Ars Scholae Palatinae
1,346
Suppose you could do it like this:

Code:
$src = array(
   array(
      "somekey1"=>"somevalue",
      "somekey2"=>"somevalue",
      "group"=>"groupName1"
    ),
   array(
      "somekey3"=>"somevalue",
      "somekey4"=>"somevalue",
      "group"=>"groupName1"
    ),
   array(
      "somekey5"=>"somevalue",
      "somekey6"=>"somevalue",
      "group"=>"groupName1"
    ),
   array(
      "somekey7"=>"somevalue",
      "somekey8"=>"somevalue",
      "group"=>"groupName2"
    ),
   array(
      "somekey9"=>"somevalue",
      "somekey10"=>"somevalue",
      "group"=>"groupName2"
  )
);

$new = array();

foreach ($src as $item) {
    $item_without_group = array_filter($item, function($value) use($item) {
        return $value !== $item['group'];
    });
    $new['group'][$item['group']][] = $item_without_group;
}

Then $new will look like this:

Code:
Array
(
    [group] => Array
        (
            [groupName1] => Array
                (
                    [0] => Array
                        (
                            [somekey1] => somevalue
                            [somekey2] => somevalue
                        )

                    [1] => Array
                        (
                            [somekey3] => somevalue
                            [somekey4] => somevalue
                        )

                    [2] => Array
                        (
                            [somekey5] => somevalue
                            [somekey6] => somevalue
                        )

                )

            [groupName2] => Array
                (
                    [0] => Array
                        (
                            [somekey7] => somevalue
                            [somekey8] => somevalue
                        )

                    [1] => Array
                        (
                            [somekey9] => somevalue
                            [somekey10] => somevalue
                        )

                )

        )

)
 

Fristie Blade

Ars Tribunus Militum
1,722
Subscriptor++
The one thing I don't get is - if your data comes out of the db anyway - why you don't sort in the db?
It seems like nothing more than one of the most simple basic queries with just an "order by" clause based on the "group" column/property.
Sorting data is best done at db level anyway instead of in a server side scripting language.

Something like: "SELECT object_id, key1, key2, group name FROM your table ORDER BY group name, object_id"

And then in one pass over the resultset you build your multi-dimensional array or structure you would like to use.
Every time you encounter a new group name, you add a new item to the 1st dimension of the array.
Then for each object / record you add an item to the 2nd dimension of the array inside the last item of the first dimension.
And if you want a third array dimension, listing the actual keys and values (excluding the object_id and the group_name) you iterate over the columns of each record and add each of their names/values as new items to the 3th level of the last item of the 2nd dimension of the last item of the 1st dimension.

Am I missing something because I see no complexity at all: just getting your dataset and iterating once over it is enough to build such a structure as long as it is sorted by the properties you would like to group your dimensions by.
 

wireframed

Ars Legatus Legionis
17,367
Subscriptor
Hey guys

Thanks for the responses - I'll try going over them and looking at the solutions. Definitely some great feedback. I'm really hung up right now, so it's not that I don't appreciate it, just haven't had time to go back and tinker with it.

[url=http:/civis/viewtopic.php?p=27986017#p27986017:1oorae5f said:
Fristie Blade[/url]":1oorae5f]The one thing I don't get is - if your data comes out of the db anyway - why you don't sort in the db?
It seems like nothing more than one of the most simple basic queries with just an "order by" clause based on the "group" column/property.
Sorting data is best done at db level anyway instead of in a server side scripting language.

Something like: "SELECT object_id, key1, key2, group name FROM your table ORDER BY group name, object_id"

And then in one pass over the resultset you build your multi-dimensional array or structure you would like to use.
Every time you encounter a new group name, you add a new item to the 1st dimension of the array.
Then for each object / record you add an item to the 2nd dimension of the array inside the last item of the first dimension.
And if you want a third array dimension, listing the actual keys and values (excluding the object_id and the group_name) you iterate over the columns of each record and add each of their names/values as new items to the 3th level of the last item of the 2nd dimension of the last item of the 1st dimension.

Am I missing something because I see no complexity at all: just getting your dataset and iterating once over it is enough to build such a structure as long as it is sorted by the properties you would like to group your dimensions by.
I'd really love to get the result out of the DB formatted in the correct arrays, I just couldn't find a way to generate a multi-dimensional array like I need, from a single query - but then I'm relatively new to SQL queries. (Newer than I am to PHP, even :p).
I'll look at your suggestion and see if it's something that could work (if nothing else, for future projects).

L.
 
Status
Not open for further replies.