Hi,
I'm busting my balls over this and it shouldn't be this difficult. Perhaps I'm making this too dificult.

I have a string of key=value pairs separated by "::" like this

142=1::144=25::14=125

What I want to end up is

Array ( [142] => 1,  [144] => 25, [14] => 125)

I thinking that at some point this would be an array of arrays, but then again it could probably be done using preg_match or preg_split, just can't crack this. please help!

    hello, you can split the original string by '::', which will result in an array of strings of the form 'a=b'. walk over this array and split each element by '='. each split will result in an array 2 elements long. say, this 2-element long array is called $pair, and your resulting array is called $result, then you will have to just do this assignment: $result[$pair[0]] = $pair[1]. hope this helps.

      konsu,
      thank you!
      yes - split - of course - I just somehow forgot that it exists and how to use it - I must have overheated. Thank you for revitalizing!

      Here's what worked for me in case anyone is interested:

      $another_array = array("142"=>"blue","145"=>"red","144"=>"green");
      $one_more_array = array("25"=>"Michael","14"=>"Sabrina","1"=>"Jane");
      
      $string = "142=1::144=25::14=125";
      
      $key_val_arr = explode("::",$string);
      
      foreach ( $ans_val_arr as $values ){
          $pieces = explode("=", $values);
          $final .= $another_array[$pieces[0]]." - ".$one_more_array[$pieces[1]].", ";
      }
      
      echo $final;
      // prints out 
      // blue - Jane, green - Michael, red - Sabrina,
      

        Well, you could have used [man]explode[/man] for both :: and =. Just thought I'd mention it.

          ideally i think you could match the string against a regular expression likecode=php*(([0-9]+)=([0-9]+))[/code]and then just work with the results of this match to build your array.

            Weedpacket wrote:

            Well, you could have used [man]explode[/man] for both :: and =. Just thought I'd mention it.

            You're right - edited the code above. Now that I think about it, may not be the best way to use the "overhead of the regular expression engine" like this for the split().

              konsu wrote:

              ideally i think you could match the string against a regular expression likecode=php*(([0-9]+)=([0-9]+))[/code]and then just work with the results of this match to build your array.

              I'm not sure I understand the purpose of the later part (after the *).

                Also perhaps I was a bit misleading in my original question about what I wanted to end up with. Thus the array as a result was not nessecarily the purpose of this but rather means to an end. Sorry about that.

                  Write a Reply...