phparrayscodeignitermatchassociate

Find matching key in two associate arrays?


I'm using codeigniter and I have a returned associated array from db like this:

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

And a long list of translated title for the keys saved as an array like this:

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

I wanted to compare the key of $result to $lang, if a key was used in $result, get its translated title. And at the end, construct an array including all three English title, translated title, and the value:

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

$data['result'] = $lang_result;

I'm storing into this format because once I passed in these data into views, I wanted to be able to call each one by name

echo "{$result['name'][0]}:  {$result['name'][1]} "; // 名字: john
echo "{$result['author'][0]}:  {$result['author'][1]} ";

So far I could only achieve this by using foreach -> switch statement

$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;
    }

}

But as the translated array gets longer, the switch statement will be ridiculously out of hands. What is a better way to simplify this?


Solution

  • As Dan mentioned array_merge_recursive may be what you want. In case you have other logic you need to implement here it is unrolled:

    $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));