'I want to merge similar data I get with foreach

There are product categories that I bought through the API service and these categories come as text. Since the categories are similar, I want to group them and print them to the database and get rid of the repetitive data.

'productTree': 'Electronic',

'productTree': 'Electronic \ Camera & Photo \ Flashes',

'productTree': 'Electronic',

'productTree': 'Electronic \ Camera & Photo \ Lenses',

'productTree': 'Electronic',

'productTree': 'Electronic \ Camera & Photo \ Lighting & Studio',

I want to group these scattered categories as follows.

'productTree': 'Electronic',
'productTree': 'Electronic\Camera & Photo\Flashes',
'productTree': 'Electronic \ Camera & Photo \ Lighting & Studio',

I want to print to database like this

Category:
id    - name        - parent_id 
1    Electronic           0
2    Camera & Photo       1
3    Flashes              2
4    Lenses               2
5    Lighting & Studio    2

I'm getting the parent_ids but I have no idea how to group all the categories

Api..
$categories = explode ("\\",$cats);
$stmt = $db->prepare("INSERT INTO cat (name, parent_id) VALUES (:name, :parent)");
$stmt->bindParam(':name', $category);
$stmt->bindParam(':parent', $parent);
$parent = 0;
foreach ($categories as $category) {
    $stmt->execute();
    $parent = $db->lastInsertId();
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source