Jump to content

How to convert text string into associative array using delimiters?


Darkwoods
Go to solution Solved by Darkwoods,

Recommended Posts

Im trying to parse/convert this string using delimiters = , | 

$text = 'cat1=hello,world|cat2=one,two|cat3=value1,value2';

 

Into an array like this:

Array(
    [cat1] => Array
        (
            [0] => hello
            [1] => world
        )

    [cat2] => Array
        (
            [0] => one
            [1] => two
        )

    [cat3] => Array
        (
            [0] => value1
            [1] => value2
        )
)

 

any suggestion on how to achieve this ?

Edited by Darkwoods
Link to comment
Share on other sites

  • Darkwoods changed the title to How to convert text string into associative array using delimiters?
  • Solution
11 minutes ago, Barand said:

explode() on the "|" to get the 3 main sections

explode each of those on "=" to get the key and the values

explode the values using ","

 

Yes this is how I managed to do it but not so sure if it looks good..

but it works

$text = 'cat1=hello,world|cat2=one,two|cat3=value1,value2';
$arr= explode('|', $text);

foreach($arr as $value)
{
	$key = rtrim(stristr($value, '=', true), '=');
	$values = ltrim(stristr($value, '='), '=');
	$values = explode(',', $values);
	$array[$key] = $values;
}

print_r($array);

 

 

 

Link to comment
Share on other sites

Here is how I would do that:

function parseDataString($inputStr)
{
    $outputAry = array();
    foreach(explode("|", $inputStr) as $catAry)
    {
        list($catName, $catValuesStr) = explode("=", $catAry);
        $outputAry[$catName]= explode(",", $catValuesStr);
    }
    return $outputAry;
}

$text = 'cat1=hello,world|cat2=one,two|cat3=value1,value2';
$result = parseDataString($inputStr);

print_r($result);
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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