multidimensional array ?

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
SpongeBob
New php-forum User
New php-forum User
Posts: 5
Joined: Tue Oct 22, 2019 7:28 am

Wed Nov 27, 2019 2:14 pm

I’m attempting to create a data structure to hold a few species of spiders. My attempt at using a multidimensional array seems to work except for the ‘location’ array. I would like to have an array that holds an array of locations but I’m having difficulty. Other than a multidimensional array is there a more suitable data structure I should be using? If not, how do I create an array of location arrays?

Code: Select all

$spiders = array(
    "species" => array("spider0", "spider1", "spider2"),
    "minLength" => array(24,17,30),
    "maxLength" => array(36,42,60),
    "bodyType" => array("medium","heavy", "thin"),
    "location" => array(
        array("location array for spider0", "Location array for spider1", "..spider2"))
);
Thank you.
User avatar
hyper
php-forum GURU
php-forum GURU
Posts: 862
Joined: Mon Feb 22, 2016 5:52 pm

Wed Nov 27, 2019 7:03 pm

The problem that you have is that it's not clear how the data is structured and it's difficult to get information back from arrays like this.

Not knowing how you expect to retrieve the data also increases the problems. A well structured database may be the solution, however, if you re-structure your array like the following:

Code: Select all

$spiders = [
  'spider0' => [
    'minLength' => '24',
    'maxLength' => '36',
    'bodyType'  => 'medium',
    'location'  => 'location of spider 0'
  ],
  'spider1' => [
    'minLength' => '17',
    'maxLength' => '42',
    'bodyType'  => 'heavy',
    'location'  => 'location of spider 1'
  ],
  'spider2' => [
    'minLength' => '30',
    'maxLength' => '60',
    'bodyType'  => 'thin',
    'location'  => 'location of spider 2'
  ]
];
I think that you will find it easier to use, (note, use the square brackets in place of array()), to get the data for each spider, you only need the name of it as the key:

Code: Select all

echo 'Minimum length = ', $spiders ['spider0'] ['minLength'];
SpongeBob
New php-forum User
New php-forum User
Posts: 5
Joined: Tue Oct 22, 2019 7:28 am

Wed Nov 27, 2019 8:00 pm

Hyper,

Thank you for the suggestions.
Post Reply