parse an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
soshea
Forum Commoner
Posts: 31
Joined: Tue Nov 12, 2002 11:22 pm
Location: Idaho
Contact:

parse an array

Post by soshea »

well i have exhausted all of my resources here, hopefully someone can give some insight. i am writing data to a .txt file onto the local server
example data:
02-12-08 23:00 1.3 10.3
(this comes off of a sensor)
sometimes the data will have more or less spaces inbetween ie (',' represents the spaces):
02-12-08 23:00,,,,-1.3,,,,,10.3
02-12-08 23:00,,,1.5,,,,,,,11.3
02-12-08 23:00,,,,0.4,,,,,,,9.3
i am utilizing fwrite to the file so only one line of data shows at a time. the problem is that when i utilize file() to get the data from .txt and put the data into an array to grab the numbers for calculations, my structure is completely thrown off due to the extra array with a " ".
if i am grabbing 02-12-08 23:00 0.4 9.3 i am calculating the numbers 0.4 and 9.3. i know that if i utilize end() i can always grab the last array 9.3, but it is the 0.4 number that is difficult. sometimes there are 3 or 4 spaces before, and sometimes there are 3 or 4 or 5 after (basically it varies). how do i get rid of the "empty" key-val pair so that my data will endup:
key[0]02-12-08
key[1]23:00
key[2]0.4
key[4]9.3
and not
key[0]02-12-08
key[1]23:00
key[3]
key[4]
key[5]0.4
key[6]
key[7]
key[8]
key[9]9.3
sorry for the lengthy question, but i did not want to confuse anyone.
any help is greatly appreciated!! and if there are any suggestions on a different path, please advise.
dusty
Forum Contributor
Posts: 122
Joined: Sun Apr 28, 2002 9:52 pm
Location: Portsmouth, VA

Post by dusty »

Code: Select all

foreach($array as $key => $val) {
  if (empty($val)) unset($array[$key]);
}
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

maybe I'm missing the point but
02-12-08 23:00,,,,-1.3,,,,,10.3
is a single line in your file? and you convert it (probably) with explode to an array? If so take a look at preg_split() as it offers
flags can be any combination of the following flags (combined with bitwise | operator):
PREG_SPLIT_NO_EMPTY
If this flag is set, only non-empty pieces will be returned by preg_split().
...
User avatar
soshea
Forum Commoner
Posts: 31
Joined: Tue Nov 12, 2002 11:22 pm
Location: Idaho
Contact:

Post by soshea »

thanx! both worked, but i went with preg_split(). less code and it replaced my explode().
appreciate the help!!
Post Reply