0

I have a little problem with multidimensional arrays. I think they are not like those in JAVA. For instance; I have created a array something like this;

$myArray = array();

Then I try to assign 4 different arrays to it as following.

$myArray[0] = $newArray0;
$myArray[1] = $newArray1;
$myArray[2] = $newArray2;
$myArray[3] = $newArray3;

But when I try to read a data from a cell with following line,

$myArray[0][2];

I could not get the data what I was hoping for. Can you guys tell me where am I mistaken?

Thanks a lot!

4
  • 3
    what is the structure of your $newArray0, $newArray1, etc? Commented May 5, 2011 at 23:18
  • 1
    You can refer to multidimensional arrays like that, so there must be something wrong with the $newArrayX variables. Commented May 5, 2011 at 23:18
  • I get the same thing in my code when I try to do $someArray[x]->someMethod(); - it just doesn't work for some reason. Commented May 5, 2011 at 23:20
  • Actually those $newArrayXs are the arrays that are kept from database. Will there be any mistake in there? I use mysql_fetch_array function and hope to create an array consisting of some part of column. Commented May 6, 2011 at 0:50

2 Answers 2

2

What you're trying to do should work, try to make sure that $newArray0 is also a numeric array and not an associative array. You can find out how your array is being setup with the following code:

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

If you've done it the right way, the output must be something similar to:

Array (
  [0] => Array (
    [1] => Value,
    [2] => Value
  ),
  [1] => Array (
    [1] => Etc,
    [2] => Etc
  )
)

If that's what it says, then $myArray[0][2] should say 'Etc'.

Sign up to request clarification or add additional context in comments.

3 Comments

What do you mean by associative array?
a numeric array is $array[0], $array[1], while an associative array contains DB fieldnames for example $array['user_id'] or $array['user_name']
Thus, if the 2nd was an associative array you would have had to use $myArray[0]['key_name'] for example. You can use mysql_fetch_array($result, MYSQL_NUM) for a numeric resultset, MYSQL_ASSOC for an associative one and MYSQL_BOTH (which is the default) to get a resultset containing both: php.net/manual/en/function.mysql-fetch-array.php
1

you got the right idea

$myArray = array();
$myArray1 = array("a","b","c");
$myArray2 = array("d","e","f");
$myArray3 = array("g","h","i");

$myArray[0] = $myArray1;
$myArray[1] = $myArray2;
$myArray[2] = $myArray3;

echo($myArray[0][2]);

WORKING DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.