Jump to content

foreach for a multi-level array


etrader

Recommended Posts

I want to create an array from a file with this structure

 

TITLE1, HEADER1, key11, key12, key13, key14

TITLE2, HEADER2, key21, key22, key23, key24

.

.

.

 

How I can get a foreach with these elements:

 

$title="TITLE"

$header="HEADER"

$key="(one random key)"

 

If needed, I can change the file structure too.

Link to comment
https://forums.phpfreaks.com/topic/235063-foreach-for-a-multi-level-array/
Share on other sites

Are you familiar with objects? If so, create an object and insert it into an array, if you want a key for this object just make use of associative arrays. The object could have your variables Title, Header, and an array containing the keys.

 

Then to loop through the array you just do:

 

foreach($objectArray as $object){
//Extract the data from the object here
}

 

Did I understand you right?

The file contains lines with TITLE, and HEADER, and some keywords

 

I am thinking of

$array=array('file.txt');
foreach ($array as $line) {
$parse=explode(",", $parse);
$title=$parse[0];
$header=$parse[1];
$key=????
}

 

The problem is that I cannot take a random from $parse[2] to $parse['last']

 

You're on the right path. Change these lines

$title=$parse[0];
$header=$parse[1];
$key=????

 

to

$title = array_shift($parse);
$header = array_shift($parse);

// $parse will now only contain the keys.
// grab a random key
$key = $parse[ array_rand($parse) ];

 

array_shift removes the first item from the array. So when it is first called it'll remove the title from the $parse array and assign it to the $title variable, the same applies for the header. You're now left with an array of keys. To grab a random key you can use array_rand.

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.