Jump to content

nested/multi dimension array


amanxman

Recommended Posts

Hi,

 

Say I have three sets of data all related, at the moment I am putting each 'set' in to it's own array and doing this:

 

$firstArray = array("a", "b", "c");
$secondArray = array ("1", "2", "3");
$thirdArray = array ("apple", "banana", "candy");

// to output
foreach ($firstArray as $key => $value)
{
echo $value;
echo $secondArray[$key];
echo $thirdArray[$key];
}

// returns "a1apple", "b2banana, "c3candy"

 

I'm thinking there must be a better (more efficient) way of doing this, by storing the 3 sets (1, a, apple) into one multidimensional array, so output is something like:

 

foreach ($multiArray as $value)
{
echo $value;
echo $value[secondlevel];
echo $value[thirdlevel];
}

 

I've read a bit on multidimensional arrays, but can't work it out...

 

Is there a better way?

 

Thanks in advance, much appreciated.

 

 

Link to comment
https://forums.phpfreaks.com/topic/264965-nestedmulti-dimension-array/
Share on other sites

Something like this?

 

<?php

$data = array(
array("1", "a", "apple"),
array("2", "b", "banana"),
array ("3", "c", "candy")
);

?>

 

and

 

<?php

$data = array(
array("1", "a", "apple"),
array("2", "b", "banana"),
array ("3", "c", "candy")
);

foreach( $data as $item ) {
echo "{$item[0]}, {$item[1]}, {$item[2]}<br>";
}

?>

 

?

 

<?php
foreach( $data as $item ) {
echo "{$item[0]}, {$item[1]}, {$item[2]}<br>";
}

?>

 

or

 

<?php

$data = array(
array("1", "a", "apple"),
array("2", "b", "banana"),
array ("3", "c", "candy")
);

foreach( $data as $arr ) {
echo join(', ', $arr) . '<br>';
}

?>

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.