0

I have two arrays same like when var_dump:

$arr1 = array (size=2)
    0 => string '10:2' 
    1 => string '10:1'

$arr2 = array (size=2)
    0 => string '[{username:userA,email:[email protected]'
    1 => string 'username:userB,email:[email protected]}]'

Now, i want to result same below:

$result = array (size=2)
    '10:2' => 
         array (size=2)
            'username' => string 'userA' 
            'email' => string '[email protected]' 

    '10:1' => 
         array (size=2)
            'username' => string 'userB' 
            'email' => string '[email protected]' 

Thanks for help!

6
  • I think that array, have to be fixed before that point Commented Sep 8, 2013 at 2:17
  • Use array_combine() to join the 2 arrays. Commented Sep 8, 2013 at 2:17
  • 2
    Why are the elements of $arr2 formatted differently? One has [{ at the beginning the other has }] at the end. Why don't those characters appear in $result? Commented Sep 8, 2013 at 2:23
  • As @Barmar said, it seems like you want to parse the values of $arr2 (usename and password) ! you aren't clear ! Commented Sep 8, 2013 at 2:32
  • $arr2 is from a json...something weird there Commented Sep 8, 2013 at 2:32

1 Answer 1

1

I think this should do it:

// Turn string "key1:val1,key2,val2,..." into associative array.
function str_to_assoc($str) {
    $str = str_replace(array('[{', '}]'), '', $str); // Remove extranous garbage
    $arr = explode(',', $str);
    $res = array();
    foreach ($arr as $keyvalue) {
        list($key, $value) = explode(':', $keyvalue);
        $res[$key] = $value;
    }
    return $res;

$result = array_combine($arr1, array_map('str_to_assoc', $arr2));

It looks like $arr2 came from improperly parsing JSON by hand (maybe using preg_split()?). If you do:

$arr2 = json_decode($json_string);

then you should be able to get your result with just:

$result = array_combine($arr1, $arr2);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for help @Barmar. It's JSON. Im using $arr2 = json_decode($json_string); $result = array_combine($arr1, $arr2); This is return same $result
Yeah, json_decode() is what I meant -- got a little confused between PHP and Javascript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.