Jump to content

String explode totally confused me


SirChick

Recommended Posts

I am so stuck here

 

I have a list of objects in categories.. and need to insert it into my database.

 

What i have is this:

 

I first have the food name followed by the types using special chars to seperate.

 

So the format is:

Food,Type1,Type2|Food,Type1,Type2| etc

 

<?php
$List =
'|"Beans","Baked"|
"Apple","Red","Green"|
"Potato","Baked","Roast"|';
?>

 

The idea is to break this up to "each food" then types of each food so I did this:

<?php
$Ex = explode('|',',', $List);
$Food = $Ex[0];
$Type = $Ex[1];
?>

Because some of them have more than one in the list for example apple has:

"Apple","Red","Green"|

 

So this means two types of apples which are red and green. But they both need to be separated for inserting into the database.

 

My table is like this:

Food table:

Name | ID

Apple |  1

 

Type table:

Type | FoodID | Primary Key

Red   |    1     |    444

Green|    1     |    445

 

 

Any tips here cos im so confused. It's so complicated to me :S

Link to comment
https://forums.phpfreaks.com/topic/117735-string-explode-totally-confused-me/
Share on other sites

Completely untested, but i'd do something like this:

 

<?php
$str = '|"Beans","Baked"| "Apple","Red","Green"| "Potato","Baked","Roast"|';
$str = str_replace('"','',$str);
$foods = array();
$types = explode('|',$str);
foreach ($types as $type){
if(!empty($type)){
	$varieties = explode(',',$type);
	for($x=1;$x<count($varieties);$x++){
		$foods[$varieties[0]][] = $varieties[$x];
	}				
}
}
foreach($foods as $type => $varieties){
$sql = "INSERT INTO sometable ('food') VALUES('$type')";
mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
$id = mysql_insert_id();
$sql = "INSERT INTO othertable ('foodid','variety') ";
$inserts = array();
foreach ($varieties as $variety){
	$inserts[] = "VALUES('$id','$variety')";
}
$insert = join(',',$inserts);
$sql .= $inserts;
mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
}
?>

 

Your first step has to be to organise the string into something more useful.

Archived

This topic is now archived and is closed to further replies.

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