Eps Posted May 9, 2011 Share Posted May 9, 2011 Hi all! This is probably fairly simple for someone who is used to dealing with arrays. I have an array of data(Parsed from an XML document) containing a string I would like to further split into another array. The string is along the lines of: "<name>":<value>,"ID":20251,"ID2":2300,"ID3":2000 How can I split the above into: Array[<NAME>] => <VALUE> Notes: <name> changes often. depending on the query, it may have different <name> values. I have been trying to do it with preg_split and got to: Array ( [0] => "<NAME>":<VALUE> [1] => "ID":20251) but I need to split it further at ":". I tried a foreach, but I failed miserably. Can anyone point me in the direction of better practice for arrays/preg_split? I have looked into the PHP documentation, but it is not enough for me. Thanks in advance Quote Link to comment https://forums.phpfreaks.com/topic/235901-array-explode-help/ Share on other sites More sharing options...
Eps Posted May 9, 2011 Author Share Posted May 9, 2011 to clarify, I want Array( [<NAME>] => <VALUE>, ID2 => "2300", ID3 => "2000"). Thanks Quote Link to comment https://forums.phpfreaks.com/topic/235901-array-explode-help/#findComment-1212689 Share on other sites More sharing options...
Eps Posted May 10, 2011 Author Share Posted May 10, 2011 Hi Guys, Still looking for some advice here. If anyone could help, it would be great Quote Link to comment https://forums.phpfreaks.com/topic/235901-array-explode-help/#findComment-1213139 Share on other sites More sharing options...
jcbones Posted May 10, 2011 Share Posted May 10, 2011 <?php $str = '"<name>":<value>,"ID":20251,"ID2":2300,"ID3":2000'; $str = str_replace('"','',$str); $ex = explode(',',$str); //break str down by comma's. foreach($ex as $part) { //cycle through the comma's. $exp = explode(':',$part); //break each part down by colon. $arr[$exp[0]] = $exp[1]; //assign the section before the colon to the key, and the section after the colon to the value. } echo '<pre>'; print_r($arr); echo '</pre>'; //show the results. ?> Quote Link to comment https://forums.phpfreaks.com/topic/235901-array-explode-help/#findComment-1213152 Share on other sites More sharing options...
Eps Posted May 10, 2011 Author Share Posted May 10, 2011 Thank you very much JCBones! I can understand how this works and is exactly what I was looking for. Quote Link to comment https://forums.phpfreaks.com/topic/235901-array-explode-help/#findComment-1213170 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.