如果我有这样的数组:
array(
"unknownString" => 34, //unknown number
"anotherString" => 32,
"asdf" => 21
);
如何将其转换为:
array(
array("unknownString", 34),
array("anotherString", 32),
array("asdf", 21)
);
答案 0 :(得分:5)
这应该有效:
$array = array(
"unknownString" => 34, //unknown number
"anotherString" => 32,
"asdf" => 21
);
$new_array = array();
foreach( $array as $key => $value) {
$new_array[] = array( $key, $value);
}
如果您愿意,还可以使用array_walk()
:
$new_array = array();
array_walk( $array, function( $el, $key) use( &$new_array){
$new_array[] = array( $key, $el);
});
答案 1 :(得分:0)
这是使用array_map
的稍微不同的版本:
function swap($value, $key) {
return array( $key, $value );
}
$arr = array(
"unknownString" => 34, //unknown number
"anotherString" => 32,
"asdf" => 21
);
print_r(array_map('swap', $arr, array_keys($arr)));