Jump to content

Create Multi-Dimensional Array


doubledee

Recommended Posts

I always seem to struggle with Arrays no matter how much I study them...

 

Could someone help me figure out how to turn this into a Multi-Dimensional Array?

 

USER	NAME	PET_ID	PETS
-----	-------	------	-------
1	Debbie

2	Sally	0	Snake
	1	Rabbit

 

Thanks,

 

 

Debbie

 

P.S.  Nothing fancy with Loops, please.

Link to comment
Share on other sites

Loops are fancy? Seriously?

 

There's a lot of ways you could structure that information, but the most obvious is to me is

<?php
$data = array();
$data[] = array('user'=>1, 'name'=>'Debbie');
$data[] = array('user'=>2, 'name'=>'Sally', 'pets'=>array(array('pet_id'=>0, 'pet'=>'Snake'), array('pet_id'=>1, 'pet'=>'Rabbit'));
?>

 

However, you should be storing this data in a DB and selecting it out. You could also use objects instead of an array.

Link to comment
Share on other sites

Loops are fancy? Seriously?

 

When I am trying to learn something new, yes!

 

 

There's a lot of ways you could structure that information, but the most obvious is to me is

<?php
$data = array();
$data[] = array('user'=>1, 'name'=>'Debbie');
$data[] = array('user'=>2, 'name'=>'Sally', 'pets'=>array(array('pet_id'=>0, 'pet'=>'Snake'), array('pet_id'=>1, 'pet'=>'Rabbit'));
?>

 

Don't you have one too many levels in there?

 

I thought that...

0, Snake
1, Rabbit

 

...was one array nested in a parent array of...

1, Debbie
2, Sally

 

 

Debbie

 

Link to comment
Share on other sites

method 1

$users = array (
    1 => array (
            'name' => 'Debbie'
            ),
    2 => array (
            'name' => 'Sally',
            'pets' => array (
                'Snake',
                'Rabbit'
            )
        )
    );

 

Method 2

$users = array (
    1 => array (
            'name' => 'Debbie'),
    2 => array (
            'name' => 'Sally')
    );
    
$users[2]['pets'][] = 'Snake';
$users[2]['pets'][] = 'Rabbit';

 

Both give the same result

Array
(
    [1] => Array
        (
            [name] => Debbie
        )

    [2] => Array
        (
            [name] => Sally
            [pets] => Array
                (
                    [0] => Snake
                    [1] => Rabbit
                )

        )

)

Link to comment
Share on other sites

Or with keeping user ID's and Pet ID's in the mix.

<?php
$data = array();
$data['user'] = array(1,2);
$data['name'] = array('Debbie','Sally');
$data['pets'] = array(
'pet_id' => array(215,133), 
'pet' => array('Snake','Rabbit')

);
echo '<pre>';
print_r($data);
echo '</pre>';
?>

Link to comment
Share on other sites

A simpler verion using name as the array key

 

<?php

$pets = array (
    'Debbie' => array(),
    'Sally'  => array()
    );
$pets['Sally'][] = 'Snake';
$pets['Sally'][] = 'Rabbit';

echo '<pre>'.print_r($pets, 1).'</pre>';
?>

 

Result

Array
(
    [Debbie] => Array
        (
        )

    [sally] => Array
        (
            [0] => Snake
            [1] => Rabbit
        )

)


Link to comment
Share on other sites

Wouldn't the original data I posted...

USER	NAME	PET_ID	PETS
-----	-------	------	-------
1	Debbie

2	Sally	0	Snake
	1	Rabbit

 

 

...logically go into a multi-dimensional array like this...

array(
1=>array(
		Debbie=>array(
				)
		)
)

2=>array(
		Sally=>array(
				0=>Snake,
				1=>Rabbit
				)
		)
)

 

The way I came to that was starting at the FAR RIGHT, and looking for a Key/Value Pair, then moving to the LEFT and looking for the next Key/Value pair, and so on...

 

0=>Snake

 

makes the inner-most array, which is nested inside...

 

Sally=>array (Sally's Pet array)

 

which is nested inside of...

 

2=>Sally

 

which is the User array.

-------

 

You could think of the right-most inner array as a "Pet array" and the middle array as an "Owner-Pet array" and the left-most outer array as a "User array", right?

 

-------

There seem to be so many ways to do things that it confuses me even more, but the above examples are how I conceptualize things in my head, and I think they visually and conceptually follow how a normalized database would work with Parent=>Child Table Relationships (i.e. One=>Many), right?!

 

 

Debbie

 

Link to comment
Share on other sites

I know your intent (well at least I assume) is to build this array from a query. 

I am going to also assume you have two tables, and yes, this is old mysql_query, sorry about that. 

I know you will remake things to your liking anyway.

<?php
$sql="SELECT u.user, u.name, p.pet_id, p.pet ";
$sql.="FROM users as u ";
$sql.="LEFT JOIN pets as p ";
$sql.="ON u.user = p.user_id";
$result=mysql_query($sql) OR DIE .mysql_error();	

$data = array();
WHILE ($row=mysql_fetch_assoc($result)){
if (isset($row['pet_id'])){
	$data[$row['user']][$row['name']][$row['pet_id']] = $row['pet'];
}else{
	$data[$row['user']] = $row['name'];
}
}
echo "<pre>";
print_r($data);
echo "</pre>";
?>

Link to comment
Share on other sites

BTW, this resulted in an array that looks like this.

Array
(
    [1] => Debbie
    [2] => Array
        (
            [sally] => Array
                (
                    [1] => Snake
                    [2] => Rabbit
                )

        )

Link to comment
Share on other sites

use objects.

Any example how to do that?  I did some searching, but didn't find anything I could get my head around to apply to this case.

 

I did come up with another version as follows.

<?php
$sql="SELECT u.user, u.name, p.pet_id, p.pet ";
$sql.="FROM users as u ";
$sql.="LEFT JOIN pets as p ";
$sql.="ON u.user = p.user_id";
$result=mysql_query($sql) OR DIE .mysql_error();	

$data = array();
WHILE ($row=mysql_fetch_assoc($result)){
	$data[$row['user']]['name'] = $row['name'];
	$data[$row['user']]['pets'][$row['pet_id']]=$row['pet'];	
}
echo "<pre>";
print_r($data);
echo "</pre>";
?>

 

Outputs

Array
(
    [1] => Array
        (
            [name] => Debbie
            [pets] => Array
                (
                    [] => 
                )

        )

    [2] => Array
        (
            [name] => Sally
            [pets] => Array
                (
                    [1] => Snake
                    [2] => Rabbit
                    [3] => Fish
                )

        )

)

Link to comment
Share on other sites

use objects.

Any example how to do that?  I did some searching, but didn't find anything I could get my head around to apply to this case.

 

Not Tested. This is very basic and can be improved on very much.

 

<?php
Class Person{
   public $id;
   public $name;
   public $pets = array();

   function __construct($id, $name, $pets=NULL){
      $this->id = $id;
      $this->name = $name;
      if($pets !== NULL){
            $this->pets = $pets;
      }
   }
}

Class Pet{
   public $type;
   public $id;

   function __construct($id, $type){
      $this->id = $id;
      $this->type = $type;
   }
}

$people = array();
$people['Sally'] = new Person(1, 'Sally'); //Could also use key of 1
$people['Debbie'] = new Person(2, 'Debbie', array(new Pet(0, 'Snake'), new Pet(1, Rabbit)); //Could do array keys here as well.
?>

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.