Jump to content

Recommended Posts

Hello again,

 

The following data structure is an example of what I have stored row by row: 0192827|Papo|019281,029182,192818|

 

I want to use a foreach loop to access the rows of data and then print out the information. The bit im having trouble with though is $key[2]. (The part of the row separated by commas.)

 

I need to separate the commas, allocate each a variable name and print them out with the rest of the information like so:

Id = 0192827

Name = Papo

Categories = 019281

                  029182

                  192818

 

My code so far is:

 

$file = file("data/manufacturers.DAT");
  foreach($file as $key => $val){
  $data[$key] = explode("|", $val);
  
  $mid = $data[$key][0];
  $manname = $data[$key][1];
  $cat_id = $data[$key][2];

$categories = explode(",", $cat_id);

print $mid;
print $manname;
print $categories;

}

 

But this won't work  :-\

 

Any help would be appreciated! Thank-you

Link to comment
https://forums.phpfreaks.com/topic/108534-solved-exploding-commas/
Share on other sites

oh I see, here try this

 

<?php
$file = file("data/manufacturers.DAT");

foreach($file as $key => $val)
{
    $data[$key] = explode("|", $val);
    
    $mid = $data[$key][0];
    $manname = $data[$key][1];
    $cats = explode(",", $data[$key][2]);

    print($mid);
    print($manname);
    print_r($cats);
}

$categories is an array containing 019281, 029182 and 192818, so you can't just print it as is. You need to loop through the elements, or implode the array (like I did below). Also simplifying it a bit:

 

<?php
$file = file("data/manufacturers.DAT");
foreach($file as $val){
  list($mid, $manname, $cat_id) = explode("|", $val);
  $categories = explode(",", $cat_id);
  
  print 'Id = ', $mid, '<br />';
  print 'Name = ', $manname, '<br />';
  print 'Categories = ', implode(',', $categories), '<br /><br />';
}
?>

 

Edit: lol, obviously it's not smart to explode the categories and then implode them, but hope you get the idea :)

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.