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

时间:2011-09-06 06:43:44

标签: php arrays hash

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循环。

1 个答案:

答案 0 :(得分:3)

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'] . ')';
}

顺便说一句,您不应该以文本格式存储时间,尤其是不存在没有时区规范的时间。而是使用timestrtotimeDateTime对象返回的UNIX时间戳。