2
$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")

替换 $data 数组中的所有值以返回的最简单方法是什么:

$data['key1'] = $key1[$data['key1']]

而不是一一做,即:

$data['key1'] = $key1[$data['key1']]
$data['key2'] = $key2[$data['key2']]...
4

4 回答 4

2

我想你正在寻找这个:

foreach($data as $k => &$v)
{
    if($$k)
    {
        $t = $$k;
        if($t[$v]) $v = $t[$v];
    }
}

print_r($data);

但我建议在这里问自己一些关于意图的更大问题

于 2013-11-05T13:39:25.087 回答
1

这个问题很难理解,但我认为你想做的是用来$data从其他数组中提取数据。如果是这种情况,这应该有效:

$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]
于 2013-11-05T13:39:40.173 回答
1

我更喜欢这个解决方案

array_walk(
    $data,
    function(&$a, $b) {
        $a = $$a[$b];
    }
);
于 2013-11-05T13:49:58.707 回答
0

您可以尝试使用 PHP 的 variables 变量,如下所示:

foreach ($data as $mkey => $mval)
{
 $data[$mkey] = $$mkey[$data[$mkey]];
}
于 2013-11-05T13:43:15.480 回答