如果$key=>value
匹配,如何删除整个数组对象?
例如,在我的数据中,我有["endDate"]=> string(10) "2017-06-24"
,如果该日期与今天date('Y-m-d')
匹配,我希望从$row
代码:
foreach ($json->data as $row)
{
$date = date('Y-m-d');
if($row->endDate == $date){
$search = array_search($date, array_column('endDate', $row));
unset($row[$search]);
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
}
JSON:
$response = $o->curl(sprintf($url, $propertyID, $pageSize, $pageNumber, $resultsFrom));
$json = json_decode($response);
答案 0 :(得分:2)
如果您在foreach中放置&符号前的&符号,则可以直接更改$ json->数据。根据你所写的内容,我认为我理解你的问题,这可能就是你所需要的。
foreach ($json->data as &$row)
{
$date = date('Y-m-d');
if ($row->endDate == $date) {
$search = array_search($date, array_column('endDate', get_object_vars($row)));
unset($row[$search]);
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
}
如果没有,请重新解释您的问题,以便我提供您需要的答案。
答案 1 :(得分:2)
$date = date('Y-m-d');
foreach ($json->data as $index=> $row){
if($row->endDate == $date) unset($json->data{$index});
}
foreach ($json->data as $row){
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
您也可以考虑跳到下一次迭代,因为看起来您正在构建来宾电子邮件列表,而不是尝试修改json供稿源。
$date = date('Y-m-d');
foreach ($json->data as $row){
if($row->endDate == $date) {
continue;
}
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
在我提出的两个选项之间,第二个选项需要的代码更少,执行时间会稍微快一些。