Schlo_50 Posted June 3, 2008 Share Posted June 3, 2008 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 More sharing options...
Prismatic Posted June 3, 2008 Share Posted June 3, 2008 <?php $str = "0192827|Papo|019281,029182,192818|"; $str_arr = explode("|", $str); $categories = explode(",", $str_arr[2]); print_r($str_arr); print_r($categories); ?> Link to comment https://forums.phpfreaks.com/topic/108534-solved-exploding-commas/#findComment-556537 Share on other sites More sharing options...
Prismatic Posted June 3, 2008 Share Posted June 3, 2008 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); } Link to comment https://forums.phpfreaks.com/topic/108534-solved-exploding-commas/#findComment-556542 Share on other sites More sharing options...
thebadbad Posted June 3, 2008 Share Posted June 3, 2008 $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 Link to comment https://forums.phpfreaks.com/topic/108534-solved-exploding-commas/#findComment-556545 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.