在数组数组中搜索数组

时间:2015-04-08 16:01:03

标签: php arrays search recursion

我发现了一些关于搜索数组的问题,但似乎没有一个能满足我的需求。

基本上我从CSV导入大量数据。我有:

$categories = array(
  [4] => array([1] => root_category, [2] => child_category, [3] => another_child, [4] => last_category),
  [8] => array([5] => root_category, [6] => child_category, [7] => another_child, [8] => last_category),
  [12] => array([9] => root_category, [10] => child_category, [11] => another_child, [12] => last_category),
);

// Category to insert:

$insert_category = array([1] => root_category, [2] => child_category, [3] => another_child, [4] => last_category);

我需要查看$insert_category中是否已存在$categories,然后我需要返回匹配的$categories数组的键(类别层次结构的结束ID)

在$ categories中,我有大约7500行的类别,$categories foreach $insert_category上的foreach循环达到最大执行时间,所以我想知道是否有更有效的方法此?

我目前正在使用这样的东西:

  if(count($categories) > 0)
  {
    foreach($categories as $key => $category)
    {
      if(count(array_diff($insert_category, $category)) === 0)
      {
        return $key;
      }
    }
  }

这给了我“超过300秒的最长执行时间”。

我正在使用的一些功能:

function get_category_parents($category_id, &$categories = array())
	{
		$db = new Database();

		$category_id = $db->prepareDBValue($category_id);

		$category = $this->get_category($category_id);

		// Append the category to the list
		$categories[] = $category;

		if($category->parentid !== '0')
		{
			// find its parent
			$SQL = "SELECT ID FROM categories WHERE ID = '$category->parentid'";

			$parentid = $db->getValue($SQL);

			if(is_numeric($parentid))
			{
				$this->get_category_parents($parentid, $categories);
			}
		}

		// No more parents, return the array
		return array_reverse($categories);
	}

function category_options($categories) 
	{
		$categoryObj = new Productcategories();

		$category_options = $categoryObj->array_flatten($categories);

		foreach($category_options as $key => $category)
		{
			if(!array_key_exists('children', (array)$category))
			{
				$parents = $categoryObj->get_category_parents($category->id);

				$chain = array();

				foreach($parents as $k => $parent)
				{
					$chain[$parent->id] = $parent->slug;
				}

				$this->options[end($parents)->id] = $chain;
			}
		}

		return true;
	}

0 个答案:

没有答案