我有一个数组$minus
array(3) { [0]=> string(6) "people"
[1]=> string(7) "friends"
[2]=> string(8) "siblings"
}
我有一个数组$user
array(3) { ["people"]=> string(3) "100"
["friends"]=> string(2) "10"
["siblings"]=> string(2) "57"
}
我可以使用$user
的值来获取$minus
的值,
echo $user[$minus[0]] . ', ' . $user[$minus[1]] . ', ' . $user[$minus[2]];
// Would echo: 100, 10, 57
但是如何通过将$user
的值用于新数组来获取$minus
的值,新数组应该是,
array(3) { [0]=> string(3) "100"
[1]=> string(2) "10"
[2]=> string(2) "57"
}
我尝试使用foreach
循环,但永远不能正确使用它?
答案 0 :(得分:4)
foreach($minus as $key=>$value) {
$new_array[$key] = $user[$value];
}
答案 1 :(得分:3)
仅使用array_map
,PHP> = 5.3
$new_array = array_map(function($item) use ($user) {return $user[$item];}, $minus);
答案 2 :(得分:1)
$new_array= array();
foreach ($minus as $key => $value){
$new_array[$key] = $user[$value];
}
print_r($new_array);
答案 3 :(得分:0)
$new_array = array($user[$minus[0]], $user[$minus[1]], $user[$minus[2]]);
答案 4 :(得分:0)
$minus = array(0 => "people",
1 => "friends",
2 => "siblings"
);
$user = array("people" => "100",
"friends" => "10",
"siblings" => "57"
);
$newArray = $minus;
array_walk($newArray,function(&$item, $key, $prefix) { $item = $prefix[$item]; },$user);
var_dump($newArray);