I've found a few questions about searching arrays but none seem to satisfy my needs.
Basically I'm importing a large set of data from a CSV. I have:
$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);
I need to see if $insert_category
already exists in $categories
and then I need to return the key (which is the end ID of the category hierarchy) of the $categories
array that matches.
In the $categories I have around 7500 rows of categories, a foreach loop over the $categories
foreach $insert_category
is hitting the max execution time so I was wondering if there is a more efficient way of doing this?
I'm currently using something like this:
if(count($categories) > 0)
{
foreach($categories as $key => $category)
{
if(count(array_diff($insert_category, $category)) === 0)
{
return $key;
}
}
}
Which is giving me "Maximum execution time of 300 seconds exceeded".
Some of the functions I'm using:
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;
}
</div>