user3770801
user3770801

Reputation: 13

PHP Multidimensional arrays keys and values

I'm really struggling to get my head around multi-dimensional arrays in PHP, my background is C and Java both of which I have no issues with arrays!

I'm trying to read from an SQL database a list of months, each month has a list of values corresponding to a value.

ie.

  2014-01-01, ("Val1", "Val2", "Val3", "Val4", "Val5"), (3, 4, 7, 5, 3)
  2014-02-01, ("Val1", "Val2", "Val3", "Val4", "Val5"), (5, 3, 6, 2, 8)
  2014-03-01, ("Val1", "Val2", "Val3", "Val4", "Val5"), (6, 5, 4, 3, 2) ...

I can read the values, I can split them down, but I want to be able to add those values to an array but putting the values into the correct month.

I c/Java I'd just create an array like this;

[0,0,0,0,0,0,0,0,0,0,0,0]  - Val1 goes in here
[0,0,0,0,0,0,0,0,0,0,0,0]  - Val2 goes in here
[0,0,0,0,0,0,0,0,0,0,0,0]
[0,0,0,0,0,0,0,0,0,0,0,0]
[0,0,0,0,0,0,0,0,0,0,0,0]  - Val5 goes in here

then as I parse through the values, I'd pick up the month, and add the values I read into the correct month.

I can create the array in PHP, all I need to know, is there a blindingly obvious way that I've missed in my coffee/sleep deprived state that I can basically say something like;

If I want to change position 11 in the the 2nd array to 6 in C I would be this;

array[2][11] = 6

is there an equivalent to do this in PHP?

Upvotes: 0

Views: 92

Answers (2)

Marcel
Marcel

Reputation: 5119

A quick example for array access

$data = [
    '2014-06-24' => ['Val1', 'Val2', 'Val3'],
    '2014-06-23' => ['Val1', 'Val2', 'Val3']
];

In PHP you have different ways for array access. The internal iterator in arrays begins with 0. Quick and dirty you can do the following.

$data['2014-06-24'][0] = 'Val4';

So your $data array will look like

$data = [
    '2014-06-24' => ['Val4', 'Val2', 'Val3'],
    '2014-06-23' => ['Val1', 'Val2', 'Val3']
];

In a more object orientated way you can use the ArrayObject class of the StandardPhpLibrary (SPL), wich brings many methods and objtects (interfaces, iterators, etc.) for dealing with arrays.

Upvotes: 0

user399666
user399666

Reputation: 19909

This would work:

$myArray[2][11] = 6;
$myArray[2][12] = 7;
var_dump( $myArray ); //view structure

Upvotes: 1

Related Questions