在两个关联数组中查找匹配的键


Find matching key in two associate arrays?

我正在使用codeigniter,我有一个从db返回的关联数组,如下所示:

 $result = ['name'=>'john', 'author'=>'smith', 'year'=>2011 ];

和键的翻译标题的长列表保存为如下数组:

$lang = ['name'=>'名字', 'author'=>'作者', 'year'=>'年份', ... ];

我想比较$result和$lang的键,如果在$result中使用了键,则获取其翻译后的标题。最后,构造一个数组,包括所有三个英文标题、翻译后的标题和值:

$lang_result = ['name'   =>['名字', 'john'],  
                'author' =>['作者', 'smith'],  
                'year'   =>['年份', 2011] ]
$data['result'] = $lang_result;

我用这种格式存储是因为一旦我将这些数据传递给视图,我希望能够按名称调用每个

echo "{$result['name'][0]}:  {$result['name'][1]} "; // 名字: john
echo "{$result['author'][0]}:  {$result['author'][1]} ";
到目前为止,我只能通过使用foreach -> switch语句 来实现这一点
$lang_result = [];
foreach ($result as $key=>$value ) {
    switch ($key){
        case 'name':
            array_push ($lang_result, [ $key => ['名字', $value] ]);
            break;
        case 'author':
            array_push ($lang_result, [ $key => ['作者', $value] ]);
            break;
    }
}

但是当转换后的数组变长时,switch语句将变得难以控制。有什么更好的简化方法吗?

正如Dan提到的array_merge_recursive可能是您想要的。如果您需要在这里实现其他逻辑,则展开:

$result = ['name'=>'john', 'author'=>'smith', 'year'=>2011];
$lang = ['name'=>'名字', 'author'=>'作者', 'year'=>'年份'];
$lang_result = [];
foreach ($result as $key=>$value) {
    if (array_key_exists($key, $lang)) {
        $lang_result[$key] = [$lang[$key], $value];
    }
}
// these are the same (for now)
print_r($lang_result);
print_r(array_merge_recursive($lang, $result));

尝试使用array_merge_recursive

$newArray = array_merge_recursive($result, $lang);

您需要将您想要的键存储到一个数组中,然后像这样执行

$lang_result = array();
$result = ['name'=>'john', 'author'=>'smith', 'year'=>2011 ];
$lang = ['name'=>'名字', 'author'=>'作者', 'year'=>'年份'];
$keys = array('name','author','year');
foreach($keys AS $key){
   if(isset($result[$key]) && isset($lang[$key])){
        $lang_result[$key] = array($result[$key],$lang[$key]);
   }
}