在PHP中将数组转换为字典

joh*_*ohn 2 php arrays dictionary

我有数组(从数据库返回),看起来像这样:

response = {
    0 = {
        id = "12312132",
        title = "title1",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    1 = {
        id = "456456456",
        title = "title2",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    2 = {
        id = "789789789",
        title = "title3",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    }
Run Code Online (Sandbox Code Playgroud)

我需要这样在字典中使用php进行转换:

response = {
    "12312132" = {
        title = "title1",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    "456456456" = {
        title = "title2",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    "789789789" = {
        title = "title3",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    }
Run Code Online (Sandbox Code Playgroud)

keyid。也许php中有一些功能,容易吗?

For*_*ien 5

dictionaryPHP中没有术语。您实际上的意思是一个associative array,通常也称为a hash。虽然是同一件事,但是这可以使将来使用Google的过程变得更容易。

您可以通过多种方式来实现,我将为您提供经典的foreach()一种。我认为array_map()方法也是可能的。

$response = ...;        // your database response
$converted = array();   // declaring some clean array, just to be sure

foreach ($response as $row) {
    $converted[$row['id']] = $row;        // entire row (for example $response[1]) is copied 
    unset($converted[$row['id']]['id']);  // deleting element with key 'id' as we don't need it anymore inside
}
print_r($converted);
Run Code Online (Sandbox Code Playgroud)