【问题标题】:php find id in 2 arrays that don't matchphp 在 2 个不匹配的数组中查找 id
【发布时间】:2021-08-07 17:58:37
【问题描述】:

我需要找到第二个数组中不存在的数组的 ID,然后知道 ID。因此例如 eventid 将与 id 相同,我需要知道 id 是否存在于第二个数组中但它确实存在于第一个数组中。

所以 10001 = 10001, 10002 = 10002, 10003 = 10003, 10004 将在第一个数组中,但不在第二个数组中。如何获得 1004 不在第二个数组中的结果。

foreach($json as $eventinsert){   

$eventid = $eventinsert['objectId'];

$event = new Google_Service_Calendar_Event(array(
  'Id' => $eventinsert['objectId'],
  'summary' => $eventinsert['name'],
  'description' => $eventinsert['name'],
  'start' => array(
    'dateTime' => $eventinsert['dateStart']
  ),`enter code here`
  'end' => array(
    'dateTime' => $eventinsert['dateEnd']
  )
));
foreach ($events as $event) {
    $start = $event->start->dateTime;
    $id = $event->id;
    if (empty($start)) {
        $start = $event->start->date;

    }
   //     printf("%s (%s)\n", $event->getSummary(), $start);
   //     printf("%s (%s)\n", $event->getSummary(), $id);
    }

【问题讨论】:

  • array_diff 够用吗?
  • 听起来您只是想要 PHP 4 以来一直存在的array_diff 函数?
  • array_diff(): 参数 #2 不是 /var/www/html/corp/calsync/insert.php 中的数组
  • 您告诉我们您有两个数组,但您的错误消息却另有说明。

标签: php arrays


【解决方案1】:

1) 情节:独特的价值

$a = [1001,1002,10003,10004];
$b = [1001,1002,10003,1005];
print_r(array_diff($a,$b)); // Array ( [3] => 10004 )

2) 情节:不是唯一值

$a = [1001,1002,10003,10003,10004,1005,1005,1005];
$b = [1001,1002,10004];
print_r(array_diff($a,$b)); // Array ( [2] => 10003 [3] => 10003 [5] => 1005 [6] => 1005 [7] => 1005 )

3) 情节:不是唯一值。但输出唯一

$a = [1001,1002,10003,10003,10004,1005,1005,1005];
$b = [1001,1002,10004];
print_r(array_unique(array_diff($a,$b))); // Array ( [2] => 10003 [5] => 1005 )

【讨论】:

  • 除了他们显然没有有两个数组。
  • print_r(array_diff($json,$events));返回 - 可恢复的致命错误:Google\Service\Calendar\Event 类的对象无法在中转换为字符串
  • print_r(array_diff($eventinsert,$event));返回 - array_diff(): 参数 #2 不是数组
  • @RyanFitz 好的,让我们说清楚。您需要比较 ($json,$events) 或 ($eventinsert,$event) 哪些变量?这些变量的值和类型是什么?你的比较功能应该放在哪里?
  • 据我现在所见。您的标题和描述与您的代码不匹配。
【解决方案2】:

成功了

//Create your variables to store the ID's of the two feeds
$ids_1 = array();
$ids_2 = array();

// Populate the arrays
foreach ($json as $item1) {
    $ids_1[] = $item1['objectId'];
 //   var_dump ($ids_1);
}
foreach ($events as $item2) {
    $ids_2[] = $item2->id;
 //   var_dump ($ids_2);
}

// Loop through the first feed, and exclude the items that are the same in the second
foreach($json as $item){
    if (!in_array($item['objectId'], $ids_2)) {
      //  echo $item->id;
    }
}

// Loop through the second feed, and exclude the items that are the same in the first
foreach($events as $item){
    if (!in_array($item->id, $ids_1)) {
        $service->events->delete($calendarId, $item->id);
        echo "Delete" . $item->id;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多