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
https://forums.phpfreaks.com/topic/263403-create-multi-dimensional-array/
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.

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

 

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
                )

        )

)

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>';
?>

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
        )

)


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

 

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>";
?>

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

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

        )

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
                )

        )

)

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.
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.