2011-09-06 156 views
-3
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 
       ) 

     ) 

) 

我想這樣=>如何從另一個php數組創建php哈希數組?

  [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循環。

+0

*(參考)* http://php.net/manual/en/language.types.array.php – Gordon

+0

和http://php.net/manual/en/control-structures.foreach.php – mario

回答

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時間戳。

+0

現在我將如何訪問/獲取'問題'的價值? – shibly