0

我正在使用 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 语句将变得荒谬失控。有什么更好的方法来简化这个?

4

3 回答 3

2

正如丹所说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));
于 2014-06-12T18:39:57.487 回答
1

尝试使用array_merge_recursive

$newArray = array_merge_recursive($result, $lang);
于 2014-06-12T18:24:00.187 回答
1

您需要将所需的密钥存储到数组中,然后像这样进行操作。

$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]);
   }
}
于 2014-06-12T18:36:23.230 回答