SirChick Posted August 1, 2008 Share Posted August 1, 2008 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 Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted August 1, 2008 Share Posted August 1, 2008 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.