Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP Array assistance

Status
Not open for further replies.

bob3940

Programmer
Dec 21, 2004
13
US
I am new to PHP and for some reason I am having an extremely hard time with arrays. I need to convert a string into a two dimensional array.

My program is being passed a string that looks like this:
field1:value1%field2:value2%field3:value3%...

There will always be a field and a value combination but the number of these sets may vary. I know that I need to use the explode function but I am having trouble with it.

My logic is something like this:

break the string into an array using the explode function on the % character so that it looks something like this

array(1)=field1:value1
array(2)=field2:value2
etc...

I then need to use the explode function on the : character in that array so that I get the something along the lines of the following

array(1,1)=Field1,value1
array(2,1)=Field2,value2
array(3,1)=Field3,value3

I am having pretty good luck with everything else in PHP but these arrays are really screwing me up.

Can you provide me with a code sample that would accomplish this?
 
Code:
$string = 'field1:value1%field2:value2%field3:value3%...';
$rows = explode('%',$string);
$data = array();
foreach($rows as $row):
  list($field,$value) = explode(':', $row);
  $data[$field] = $value;
endforeach;
print_r($data);

you could also use str_getcsv()
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top