Reputation: 1283
$data = Array ( ['key1'] => 1 , ['key2'] => 20 , ['key3'] => 11)
$key1 = Array (1 => "a" , 2 => "b")
$key2 = Array (1 => "a" , .... 20 => "y")
$key3 = Array (1 => "a" , .... 11 => "n")
what is the easiest way to replace all values in $data array to return:
$data['key1'] = $key1[$data['key1']]
instead of doing that one by one i.e:
$data['key1'] = $key1[$data['key1']]
$data['key2'] = $key2[$data['key2']]...
Upvotes: 2
Views: 98
Reputation: 16768
I think you are looking for this:
foreach($data as $k => &$v)
{
if($$k)
{
$t = $$k;
if($t[$v]) $v = $t[$v];
}
}
print_r($data);
but I'd suggest asking yourself some bigger questions about the intent here
Upvotes: 2
Reputation: 4906
i'd prefer this solution
array_walk(
$data,
function(&$a, $b) {
$a = $$a[$b];
}
);
Upvotes: 1
Reputation: 2399
The question is quite hard to understand, but I think what you're trying to do is use $data
to pull data from the other arrays. If that's the case, this should work:
$data = array('key1' => 1, 'key2' => 2, 'key3' => 0);
$key1 = array(1,2,3,4,5);
$key2 = array(6,7,8,9,10);
$key3 = array(11,12,13,14);
foreach(array_keys($data) as $key) {
if(isset($$key)) {
$target = $$key;
$value = $target[$data[$key]];
$data[$key] = $value;
}
}
var_dump($data); #=> [key1 => 2, key2 => 8, key3 => 11]
Upvotes: 1
Reputation: 101
You could try using PHP's variables variables, something like this:
foreach ($data as $mkey => $mval)
{
$data[$mkey] = $$mkey[$data[$mkey]];
}
Upvotes: 0