拆分关联数组

时间:2015-03-03 07:16:51

标签: php yii

我正在尝试拆分一个关联数组。但是,它只是删除它的键并按升序排序。我想用关键字和值来获得关联数组的前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);

2 个答案:

答案 0 :(得分:0)

您可以使用array_slice

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

答案 1 :(得分: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);