简体   繁体   中英

PHP array values to associative array keys?

Is there a quick/easy PHP function to take the VALUES of an array and create an new associative array from the value mappings? or is this a classic iterate, parse, and add?

Example, source array in var_dump() form:

array(3) { 
    [0]=> string(36) "md5=397f7a7501dfe5f18c1057885d698d5d" 
    [1]=> string(7) "foo=bar" 
    [2]=> string(7) "t=18351" 
}

Should be converted to an associative array:

array(3) {
    ["md5"]=> string(32) "397f7a7501dfe5f18c1057885d698d5d"
    ["foo"]=> string(3) "bar" 
    ["t"]=> string(5) "18351"
}

Try this:

$myArray = array(); // Fill with values in your example
$string_to_parse = implode('&', $myArray);
parse_str($string_to_parse, $result);
var_dump($result);

If your array gets much more complex, with duplicate key/value pairs or other situations, this solution might not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM