我只是想知道如何从另一个数组创建一个数组。我有这个多维数组。
Array(
[0] => Array(
[c] => Array(
[0] => Array(
[v] => Commercial
)
[1] => Array(
[v] => 2
)
)
)
[1] => Array(
[c] => Array(
[0] => Array(
[v] => Infrastructure
)
[1] => Array(
[v] => 47
)
)
)
[2] => Array(
[c] => Array(
[0] => Array(
[v] => Tourist & Recreational
)
[1] => Array(
[v] => 3
)
)
)
)
我想从上面的数组中动态创建以下数组。
Array
(
[Commercial] => 2
[Infrastructure] => 47
[Tourist & Recreational] =3
)
感谢任何帮助。
答案 0 :(得分:1)
假设您的上述数组位于$ array中。所以,
$new_arr = array();
foreach($array as $val){
if(isset($val['c'][0]['v']) && isset($val['c'][1]['v'])){
$new_arr[$val['c'][0]['v']] = $val['c'][1]['v'];
}
}
print_r($new_arr);
答案 1 :(得分:0)
在这种情况下,array_walk_recursive()函数是你的答案,这个解决方案有点脏,但是一般函数只能在Leaf节点上运行,所以它绝对是要走的路:
<?php
$arr = [
0 => [
'c' => [
0 => [
'v' => 'Commercial'
] ,
1 => [
'v' => 2
] ,
]
],
1 => [
'c' => [
0 => [
'v' => 'Infrastructure'
] ,
1 => [
'v' => 47
] ,
]
],
2 => [
'c' => [
0 => [
'v' => 'Tourist & Recreational'
] ,
1 => [
'v' => 3
] ,
]
]
];
global $array_clean;
function pluck_leaves( $item, $key ) {
global $array_clean;
if ( is_numeric( $item ) ) {
if ( isset( $array_clean['temp_key'] ) ) {
$array_clean[$item] = $array_clean['temp_key'];
unset( $array_clean['temp_key'] );
} else {
$array_clean[$item] = null;
}
} else {
$last_key = key(end($array_clean));
reset( $array_clean );
if ($array_clean[ $last_key ] !== null) {
$array_clean[ $last_key ] = $item;
} else {
$array_clean['temp_key'] = $item;
}
}
}
array_walk_recursive($arr, 'pluck_leaves' );
var_dump($array_clean);
?>