基于数据库的主键id在php中重建索引数组

时间:2013-12-17 07:54:13

标签: php

我有一个ORM查询返回的以下数组

array(
    (int) 0 => array(
        (int) 0 => array(
            'id' => '11',
            'name' => 'branch11',
            'code' => '018',
            'server_name' => '****',
            'user_name' => 'usr1',
            'pass_name' => '***',
            'database_name' => '***',
            'sct_mapping_code' => '318'
        )
    ),
    (int) 1 => array(
        (int) 0 => array(
            'id' => '12',
            'name' => 'Branch1',
            'code' => '001',
            'server_name' => 'SRVR1',
            'user_name' => '****',
            'pass_name' => '****',
            'database_name' => '***',
            'mapping_code' => '301'
        )
    )

)

我需要将其更改为

array
('11'=> array(
                'name' => 'branch11',
                'code' => '018',
                'server_name' => '****',
                'user_name' => 'usr1',
                'pass_name' => '***',
                'database_name' => '***',
                'sct_mapping_code' => '318'
            ),
    '12'=>array(
                'name' => 'Branch1',
                'code' => '001',
                'server_name' => 'SRVR1',
                'user_name' => '****',
                'pass_name' => '****',
                'database_name' => '***',
                'mapping_code' => '301'
            )
)

我需要将id => 11和id => 12作为新数组的索引

2 个答案:

答案 0 :(得分:2)

好处是在PHP中,索引数组实际上也只是关键数组,其中键是整数。所以,你可以这样做:

$myArray = array()

foreach($objects as $obj) {
      $myArray[(int)$obj->id] = $obj;
}

(修改该代码以满足您的需求)。

答案 1 :(得分:1)

您可以使用简单循环并将记录分配给新数组:

$newArr = array();

foreach ($yourArray as $rec)
{
    $id = $rec['id'];
    unset($rec['id']);
    $newArr[$id] = $rec;
}

unset($yourArray);  //you might unset your old array so the garbage collector would free up some memory