将选定数量的每种注册类型添加到数组时,如何解决未定义的索引错误?

时间:2018-07-03 14:15:02

标签: php laravel eloquent

我想用以下代码获取每种注册类型的数量:

$registrationTypeDetails = Registration::with('participants:id,registration_type_id,registration_id')->find($regID);

$type_counts = [];
foreach ($registrationTypeDetails->participants as $p) {
    $name = $p->registration_type->name;
    if (!isset($type_counts[$name])) {
        $type_counts[$name] = 0;
    }
    $type_counts[$name]++;
}

dd($type_counts),如果会议有2种注册类型可用(普通和加号),并且用户正在使用2种注册类型“ 普通”和0种注册类型“ ”显示:

 array:2 [▼
      "general" => 2
    ]

所以工作正常。但是然后我需要向API发出发布请求,以便在请求主体中发送每种注册类型的数量,在这种情况下,对于注册类型“ 普通”,该值应为“ 2“。

但是它无法正常工作,显示为"Undefined index: plus"

您知道问题出在哪里吗?

    foreach($registration->conference->registrationTypes as $key=>$registrationType){
       $items['invoice']['items'][]  = [
   'name' => $registration->conference->registrationTypes[$key]['name'],
   'unit_price' => $registration->conference->registrationTypes[$key]['price'],
   'quantity' =>  $type_counts[$registration->conference->registrationTypes[$key]['name']], // error is here
            ];
        }

        $create = $client->request('POST', 'https://...', [
            'query' => ['api_key' => '...'], 'json' => $items,
        ]);

包含项的数组应类似于:

 array:1 [▼
  "invoice" => array:4 [▼
    "items" => array:2 [▼
      0 => array:5 [▼
        "name" => "general"
        "unit_price" => 10
        "quantity" => 2
      ]
    ]
  ]
]

dd($registration->conference->registrationTypes)显示与会议相关的两种注册类型(常规和加号):

Collection {#337 ▼
  #items: array:2 [▼
    0 => RegistrationType {#330 ▼
      +wasRecentlyCreated: false
      #attributes: array:11 [▼
        "id" => 1
        "name" => "general"
        ...
      ]
    }
    1 => RegistrationType {#345 ▼
      #attributes: array:11 [▼
        "id" => 2
        "name" => "plus"
        ...
      ]
        ...
    }
  ]
}

问题在于何时未选择任何注册类型“ plus”。如果用户仅选择类型为“常规”的注册类型,则会显示“未定义的索引:加号”,但是如果用户选择类型为“常规”但也为“加号”的注册类型,则不会出现错误。例如,如果$ type_counts如下所示,则不会出现错误:

array:1 [▼
  "geral" => 2,
  "plus"  => 1
]

0 个答案:

没有答案