2015-03-03 95 views
0

我想分割一個關聯數組,但發生的是它只是刪除它的鍵並按升序排列。我想用鍵和值來獲得關聯數組的前5個元素。拆分關聯數組

$AllQuestions = Question::model()->findAll($criteria); 
     foreach ($AllQuestions as $aq) { 
      $question = array(); 
      $question[$aq->id] = $aq->question; 
      if ($aq->type == "Realistic") { 
       $testViewModel->RealisticQuestions[$aq->id] = $aq->question; 
      } else if ($aq->type == "Investigative") { 
       $testViewModel->InvestigativeQuestions[$aq->id] = $aq->question; 
      } else if ($aq->type == "Conventional") { 
       $testViewModel->ConventionalQuestions[$aq->id] = $aq->question; 
      } else if ($aq->type == "Enterprising") { 
       $testViewModel->EnterpriseQuestions[$aq->id] = $aq->question; 
      } else if ($aq->type == "Social") { 
       $testViewModel->SocialQuestions[$aq->id] = $aq->question; 
      } else if ($aq->type == "Artistic") { 
       $testViewModel->ArtisticQuestions[$aq->id] = $aq->question; 
      } 
     } 
     $testViewModel->InvestigativeQuestions = array_slice($testViewModel->InvestigativeQuestions, 0, $maxQuestions); 
     $testViewModel->ArtisticQuestions = array_slice($testViewModel->ArtisticQuestions, 0, $maxQuestions); 
     $testViewModel->ConventionalQuestions = array_slice($testViewModel->ConventionalQuestions, 0, $maxQuestions); 
     $testViewModel->EnterpriseQuestions = array_slice($testViewModel->EnterpriseQuestions, 0, $maxQuestions); 
     $testViewModel->SocialQuestions = array_slice($testViewModel->SocialQuestions, 0, $maxQuestions); 
     $testViewModel->RealisticQuestions = array_slice($testViewModel->RealisticQuestions, 0, $maxQuestions); 
+1

你嘗試過什麼?一小段代碼對於試圖更好地理解你的問題的人會有所幫助 – 2015-03-03 07:18:17

+0

你能告訴我們一些你到目前爲止嘗試過的代碼嗎? – 2015-03-03 07:19:00

+0

@VivekPradhan這是我到目前爲止所嘗試的 – 2015-03-03 07:23:50

回答

0

您可以使用array_slice

$new_array = array_slice($old_array, 0, 5, true); 
0
Use it: 

$testViewModel->InvestigativeQuestions = array_slice($testViewModel->InvestigativeQuestions, 0, $maxQuestions, true); 
$testViewModel->ArtisticQuestions = array_slice($testViewModel->ArtisticQuestions, 0, $maxQuestions, true); 
$testViewModel->ConventionalQuestions = array_slice($testViewModel->ConventionalQuestions, 0, $maxQuestions, true); 
$testViewModel->EnterpriseQuestions = array_slice($testViewModel->EnterpriseQuestions, 0, $maxQuestions, true); 
$testViewModel->SocialQuestions = array_slice($testViewModel->SocialQuestions, 0, $maxQuestions, true); 
$testViewModel->RealisticQuestions = array_slice($testViewModel->RealisticQuestions, 0, $maxQuestions, true);