【问题标题】:Why does my foreach-loop outputs only one checklistItem? (PHP)为什么我的 foreach 循环只输出一个 checklistItem? (PHP)
【发布时间】:2020-12-10 16:27:11
【问题描述】:

我的目标是获取所有 userChecklistItems 的数组,但循环只返回一个值。我认为这与类别数组有关,但我找不到解决方案...

private $responseJson = [];

public function getArray($user) {
    
    $responseJson['checklistItems'] = [
        ChecklistItem::CATEGORY_DAY => [],
        ChecklistItem::CATEGORY_WEEK => [],
        ChecklistItem::CATEGORY_MONTH => [],
        ChecklistItem::CATEGORY_ONE_HUNDRED_DAYS => []
    ];

    $userChecklistItems = $user->getUserChecklistItems();

    foreach($userChecklistItems as $userChecklistItem) {
        $category = $userChecklistItem->getChecklistItem()->getCategory();
        $responseJson['checklistItems'][$category] = [
            'text' => $userChecklistItem->getChecklistItem()->getText(),
            'isChecked' => $userChecklistItem->getIsChecked()
        ];
    };
    
    return $responseJson;
}

【问题讨论】:

    标签: php arrays foreach


    【解决方案1】:

    好的,我明白了 - newArray 不见了

    $userChecklistItems = $user->getUserChecklistItems();
        $newArray = [];
    
        foreach($userChecklistItems as $userChecklistItem) {
            $category = $userChecklistItem->getChecklistItem()->getCategory();
            $responseJson['checklistItems'][$category] = [
                'text' => $userChecklistItem->getChecklistItem()->getText(),
                'isChecked' => $userChecklistItem->getIsChecked()
            ];
            $newArray[] = $responseJson;
        };
        
        return $newArray;
    

    【讨论】:

      猜你喜欢
      • 2014-12-15
      • 2013-11-06
      • 2018-08-21
      • 2022-01-23
      • 2012-02-10
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多