简体   繁体   English

PHP 数组值到关联数组键?

[英]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?是否有一个快速/简单的 PHP 函数来获取数组的 VALUES 并从值映射中创建一个新的关联数组? or is this a classic iterate, parse, and add?或者这是一个经典的迭代、解析和添加?

Example, source array in var_dump() form:例如, var_dump()形式的源数组:

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.如果您的数组变得更加复杂,存在重复的键/值对或其他情况,则此解决方案可能不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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