Reputation: 551
I am trying to echo a single element from an array stored in the cell of the parent array. For the sake of readability, we'll call the parent array $parent and the child array $child. I want to echo the 2nd element from $child. When I use the code:
echo "$parent[0][1]";
I get the array to string conversion error followed by the text "[1]". As I understand it, "$parent[0]" should be interpreted as $child, so that the following [1] would request the second element from $child. Clearly, this is not happening, and the only part that is being read is $parent[0] which is then thrown back because that element is an array.
Also, my $parent array is populated by a looped function which pulls data from a table, so it's simpler to leave its elements in numeric form. In specific, each element of $parent holds the id# and date of a round of golf, retrieved from a table full of rounds of golf. My function pulls them using mysql_query and looped mysql_get_row when then stores in my $parent array.
I realize there's a lot of unnecessary information here, but I'm hoping it helps avoid solutions that are unworkable in my specific situation. My basic question is, how to echo an element from an array nested within another array.
Thanks in advance.
Edit after answer
The below answers work perfectly, but I also found a dirty workaround. Assigning the $child array to a placeholder and then printing from the placeholder works, but it requires a few more lines of code and doesn't look pretty.
eg.
$holdArray = $parent[0];
echo "$holdArray[1]";
Thanks again for the quick and helpful responses. As always the SE community comes through.
Upvotes: 3
Views: 7276
Reputation: 32730
Here is another solution if your array contains many sub arrays and you want to show then each.
foreach($parent as $child){
echo $child[1];
echo "<br>";
}
If your array contains only single child array yo can do it like this :
$array = array(array(1,'edwards',"somesong.mp3"));
list($child) = $array;
echo $child[0]; // this will print 1
OR
echo $parent[0][1];
Upvotes: 1
Reputation: 429
Try with
echo "{$parent[0][1]}";
Demo: http://codepad.org/bAfbg1Fh
Upvotes: 1
Reputation: 3160
echo "{$parent[0][1]}";
OR echo $parent[0][1];
should work
OR if your array is a associative try: echo "{$parent['foo']['bar']}";
OR echo $parent['foo']['bar'];
Upvotes: 1