1

如果我有这样的数组:

array(
    "unknownString" => 34, //unknown number
    "anotherString" => 32,
    "asdf" => 21
);

我怎样才能把它转换成这个:

array(
    array("unknownString", 34),
    array("anotherString", 32),
    array("asdf", 21)
);
4

2 回答 2

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); 
});
于 2012-07-13T18:39:17.990 回答
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)));
于 2012-07-13T18:48:07.897 回答