I have an array $minus
array(3) { [0]=> string(6) "people"
[1]=> string(7) "friends"
[2]=> string(8) "siblings"
}
And I have an array $user
array(3) { ["people"]=> string(3) "100"
["friends"]=> string(2) "10"
["siblings"]=> string(2) "57"
}
I can get the values of $user
by using the values of $minus
like,
echo $user[$minus[0]] . ', ' . $user[$minus[1]] . ', ' . $user[$minus[2]];
// Would echo: 100, 10, 57
But how can I get the values of $user
by using the values of $minus
into a new array, the new array should be like,
array(3) { [0]=> string(3) "100"
[1]=> string(2) "10"
[2]=> string(2) "57"
}
I have tried using foreach
loops but can never get it right?
foreach($minus as $key=>$value) {
$new_array[$key] = $user[$value];
}
Use array_map
, PHP >= 5.3 only
$new_array = array_map(function($item) use ($user) {return $user[$item];}, $minus);
$new_array = array($user[$minus[0]], $user[$minus[1]], $user[$minus[2]]);
$new_array= array();
foreach ($minus as $key => $value){
$new_array[$key] = $user[$value];
}
print_r($new_array);
$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);