Jump to content

Recommended Posts

Here's the string: 

 

415{3}8{1}1{6}35

 

I'm trying to:

1. drop first element - 415

2. convert rest of string to an array in this way:

 

array([3]=>8 [1]=>1 [6]=>35)

 

Seems simple enough, but somehow I do something wrong.

Here's what I try to do:

 

$s = explode('{', '415{3}8{1}1{6}35');

I get:

Array ( [0] => 3}8 [1] => 1}1 [2] => 6}35 )

 

I tried to walk this array using foreach and exploding values, but I can't find (so far) a way to actually get this:

 

Array ([3]=>8 [1]=>1 [6]=>35)

 

Any thoughts which can put me on a right track?

Thanx in advance.

Link to comment
https://forums.phpfreaks.com/topic/127528-solved-2-separator-string-to-array/
Share on other sites

ghostdog74 thank you - I will definitely have to explore regex.

 

Your solution gets this:

 Array ( [0] => 415 [1] => 8 [2] => 1 [3] => 35 ) 

 

while I look to accomplish this:

 Array ([3]=>8 [1]=>1 [6]=>35) 

 

Inside of curly braces become keys and what follows, becomes values of a new array

 

Anyone has an idea?

Thank you thorpe.

Your solution brings this:

 Array ( [0] => 5 [1] => 8 [2] => 1 [3] => 35 ) 

 

I was actually looking for this:

Array ([3]=>8 [1]=>1 [6]=>35)

 

I actually did it this way (not very elegant/compact, but does the job).

$entry_array = '415{3}8{1}1{6}35';
$str = str_replace(array('{','}'),',',$entry_array);
$array = explode(',',$str);
array_shift($array);

foreach ($array as $k => $v)
	{
		if (!is_odd($k)) $key_array[] = $v;//even
		if (is_odd($k)) $val_array[] = $v; //odd
	}	
    //for loop below is for PHP4
    //PHP5 has function for it: array_combine
    for ($i=0, $n=sizeof($key_array); $i<$n; $i++) 
	{
		$new_array[$key_array[$i]] = $val_array[$i];
	}

print_r($new_array);

 

A little function is needed here (checks even/odd - only if array_combine is not used):

function is_odd($number) {
   return $number & 1; // 
}

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.