我如何从另一个php数组创建php哈希数组


How can i create php hash array from another php array?

Array
(
    [0] => Array
        (
            [Poll] => Array
                (
                    [id] => 1
                    [question] => What's your favourite linux distribution ?
                    [mark] => 1
                    [created] => 2011-09-05 20:30:57
                    [modified] => 2011-09-05 20:30:57
                )
        )
    [1] => Array
        (
            [Poll] => Array
                (
                    [id] => 2
                    [question] => What's your favourite editor ?
                    [mark] => 1
                    [created] => 2011-09-05 20:31:59
                    [modified] => 2011-09-05 20:31:59
                )
        )
)

我想得到这样的数组=>

            [Poll] => Array
                (
                    [id] => 1
                    [question] => What's your favourite linux distribution ?
                    [mark] => 1
                    [created] => 2011-09-05 20:30:57
                    [modified] => 2011-09-05 20:30:57
                )
            [Poll] => Array
                (
                    [id] => 2
                    [question] => What's your favourite editor ?
                    [mark] => 1
                    [created] => 2011-09-05 20:31:59
                    [modified] => 2011-09-05 20:31:59
                )

是否有任何php函数来做到这一点或任何快捷方式?我知道foreach循环

php数组中的每个键必须是唯一的。因此,不能有array("Poll"=>array(), "Poll"=>array());。但是,您可以使用以下

$r = array_map(function($subArray) {
  return $subArray['Poll'];
}, $inputArray);

这将使$r成为这样的数组:

array(
  array(
    "id" => 1,
    "question" => "What's your favourite linux distribution ?",
    "mark" => 1,
    "created" => "2011-09-05 20:30:57",
    "modified" => "2011-09-05 20:30:57",
  ),
  array(
    "id" => 2,
    "question" => "What's your favourite editor ?",
    "mark" => 1,
    "created" => "2011-09-05 20:31:59",
    "modified" => "2011-09-05 20:31:59"
  )
);

你可以这样使用:

foreach($r as $qar) {
  echo $qar['question'] . ' (Created ' . $qar['created'] . ')';
}
顺便说一下,您不应该以文本格式存储时间,特别是在没有时区规范的格式中。相反,使用由timestrtotime返回的UNIX时间戳,或者使用DateTime对象。