Jump to content

Array explode help!


Eps

Recommended Posts

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 :)

Link to comment
https://forums.phpfreaks.com/topic/235901-array-explode-help/
Share on other sites

<?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.
?>

Link to comment
https://forums.phpfreaks.com/topic/235901-array-explode-help/#findComment-1213152
Share on other sites

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.