如何简化我的数组代码


How to simplify my array codes

我试图将我的db返回的结果分配给数组

$results = Db::get('get_items', array('id' =>$id));
$Info['items'][1]['title'] = $results[0]['Name'];
$Info['items'][1]['name'] = $results[0]['Filename'];
$Info['items'][1]['type'] = $results[0]['Type];

数据库只返回1行数据。

我需要我的$info看起来像下面的

Array
(
    [items] => Array
        (
            [1] => Array
                (
                    [title] => Title test
                    [filename] => test.xml
                    [type] => company
                )
        )
    [mis] => data
)

我想知道是否有更好的方法将值分配给$info而不仅仅是hardcoded。非常感谢!

使用数组来描述键映射:

$map = array('Name' => 'title',
             'Filename' => 'name',
             'Type' => 'type');
foreach ($results[0] as $key => $value) {
    $Info['items'][1][$map[$key]] = $value;
}

当您想要执行某种一对一的转换时,您应该立即考虑使用关联数组。

更改您的查询,以便您获得字段作为您想要的字段名称。我不知道你的DB类是做什么的,但是你可以用mySQL

SELECT `Filename` as `name` FROM table;

那么你可以这样做:

$Info['items'][1] = $results[0];