PHP - 比较2个数组

时间:2015-07-28 09:59:34

标签: php arrays

我有2个数组。 $child包含来自多个类别的product_id列表。 $parent包含$child类别的父类别中的product_id。

所有$child个ID都应在$parent

之内

父级目前包含1140条记录,而子级包含1305条,因此有165条子记录应该在父级内。

array_diff只显示了1条记录,我做错了什么?

<?php

  require_once 'app/Mage.php';
  umask(0);
  Mage::app();

  $connection = Mage::getSingleton('core/resource')->getConnection('core_read');
  $sql        = "Select product_id FROM catalog_category_product WHERE (category_id = 16 OR category_id = 17 OR category_id = 18 OR category_id = 20 OR category_id = 21 OR category_id = 22 OR category_id = 23 OR category_id = 24 OR category_id = 25 OR category_id = 63 OR category_id = 64 OR category_id = 65 OR category_id = 66 OR category_id = 67 OR category_id = 68 OR category_id = 876 OR category_id = 877 OR category_id = 878 OR category_id = 879 OR category_id = 880 OR category_id = 883) ORDER BY product_id";
  $rows       = $connection->fetchAll($sql);

  $child = array();

  foreach ($rows as $row) {     
    $child[] = $row['product_id'];      
  }

  echo count($child);

  //print_r($prod);

  $sql        = "Select product_id FROM catalog_category_product WHERE category_id = 10 ORDER BY product_id";
  $rows       = $connection->fetchAll($sql);

  $parent = array();

  foreach ($rows as $row) {     
    $parent[] = $row['product_id'];     
  }

  echo "<br />";
  echo "<br />";
  echo "<br />";
  echo "<br />";

  echo count($parent);

  //print_r($category);

  echo "<br />";
  echo "<br />";
  echo "<br />";
  echo "<br />";

  $add=array_diff($child,$parent);
  //echo count($add);

  print_r($add);

?>

1 个答案:

答案 0 :(得分:0)

我的错误,$child数组包含重复项。我添加了一个GROUP BY子句,1305个结果降到了1124。