Jump to content

Sorting multidimensional array


Nico7430

Recommended Posts

I want to create an array based on data in a multidimensional array. Take, for example:

 

$table[1] = array('husband' => array ('firstname'=> 'Albert',

                                                          'lastname' => 'Einstein',

                                                          'age'      => 129),

                          'wife'        => array ('firstname' => 'Mileva',

                                                          'lastname'  => 'Einstein',

                                                          'age'      => 128));

 

What would be the best approach, when you want to

create an array with only the last names or the ages? Are there some

things like wildcards in the PHP array universe to skip the first array level?

 

Any suggestion is very appreciated. I tried several strategies, but ended up creating the same mulitdimensional array as above.

Link to comment
Share on other sites

Something like this I'd guess:

 

$ages = $lastnames = array();

foreach($table[1] as $type => $person) {
   $ages[$type] = $person['age'];
   $lastnames[$type] = $person['lastname'];
}

print_r($ages);
print_r($lastnames);

Link to comment
Share on other sites

@ Jasonrichardsmith: I have to admit that what I am searching for, is a bit more complicated than my first post in this thread. I work a lot with xml and try to understand how php works with xml. Every time I import attributes and want to do something with them (sort them, select them, etcetera), I get those multidimensional arrays which I don't know how to use...

 

The problem looked very much like the example I gave in my first post here. Indeed, I took that example from the Wrox introduction on php, but I have to say... the first time I saw that example, I wondered already what somebody needed to do when he/she would like to use this array in a way it was not designed for...

 

I can put my whole project here, but... I rather like to put it simple and then try it further on my own.

 

Silkfire: thanks a lot! It works. That was the code I was looking for.  :shy:

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.