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
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?

Link to comment
Share on other sites

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']

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.