在php中将数组转换为字典

时间:2015-03-04 13:50:06

标签: 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"
        }
    }

我需要在字典中使用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"
        }
    }

即。 keyid。也许php中有一些功能,为了方便吗?

3 个答案:

答案 0 :(得分:4)

PHP中没有dictionary个术语。你的意思是associative array,通常称为hash。同样的事情,但这可以使将来更容易谷歌。

你可以通过多种方式完成,我会给你一个经典的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);

答案 1 :(得分:0)

不,但你可以用PHP编写一个小程序:

$result = array();
foreach ($response as $row)
{
  $id = $row['id'];
  unset($row['id']);
  $result[$id] = $row;
}

echo '<pre>';
print_r($result);
echo '</pre>';

甚至将它变成你自己的功能:

function dictonary($response) 
{
  $result = array();
  foreach ($response as $row)
  { 
    $id = $row['id'];
    unset($row['id']);
    $result[$id] = $row;
  }
  return $result;
}

答案 2 :(得分:0)

循环结果以新格式再次填充数组

    $count = count($response) // count the items of your initial array
    $i=0;
    while($i<$count) { //start a loop to populate new array
    $key = $response[i]['id'];
    $new_response[$key] = array('title' =>  $response[i]['title'], ... ,'createDT' => $response[i]['createDT']);
    $i++;
    } // end loop

print_r($new_response);