<?php array ( 0 => array ( 'id' => 'users', 'title' => 'Users', 'items' => array ( 0 => array ( 'id' => 'user_1', ), 1 => array ( 'id' => 'user_1', ), ), ), 1 => array ( 'id' => 'players', 'title' => 'Players', 'items' => array ( 0 => array ( 'id' => 'player_1', ), ), ), 2 => array ( 'id' => 'employees', 'title' => 'Employees', 'items' => array ( 0 => array ( 'id' => 'employees_1', ), 1 => array ( 'id' => 'employees_2', ), ), ), 3 => array ( 'id' => 'programmers', 'title' => 'Programmers', 'items' => array ( 0 => array ( 'id' => 'programmer_1', ), 1 => array ( 'id' => 'programmer_2', ), ), ), ); class ArrayCombiner { private $data; public function __construct(array $data) { $this->data = $data; } public function combineAndMerge(array $idsToCombine, $newId, $newTitle) { // Find indices of $idsToCombine in $this->data $indices = $this->findIndicesByIds($idsToCombine); if (count($indices) !== count($idsToCombine)) { return false; // Not all elements were found } // Extract items arrays from $indices $mergedItems = []; foreach ($indices as $index) { $mergedItems = array_merge($mergedItems, $this->data[$index]['items']); } // Create new combined element $combinedElement = [ 'id' => $newId, 'title' => $newTitle, 'items' => $mergedItems, ]; // Remove elements from $this->data based on $indices foreach ($indices as $index) { unset($this->data[$index]); } // Add $combinedElement to $this->data $this->data[] = $combinedElement; // Reindex the array $this->data = array_values($this->data); return true; } public function getData() { return $this->data; } private function findIndicesByIds(array $ids) { $indices = []; foreach ($this->data as $index => $element) { if (in_array($element['id'], $ids)) { $indices[] = $index; } } return $indices; } } // Example usage: $data = [ [ 'id' => 'users', 'title' => 'Users', 'items' => [ ['id' => 'user_1'], ['id' => 'user_2'], ], ], [ 'id' => 'players', 'title' => 'Players', 'items' => [ ['id' => 'player_1'], ], ], [ 'id' => 'employees', 'title' => 'Employees', 'items' => [ ['id' => 'employee_1'], ['id' => 'employee_2'], ], ], [ 'id' => 'programmers', 'title' => 'Programmers', 'items' => [ ['id' => 'programmer_1'], ['id' => 'programmer_2'], ], ], ]; $combiner = new ArrayCombiner($data); // Combine 'users', 'players', 'employees', and 'programmers' into 'combined_group' $combiner->combineAndMerge(['users', 'players', 'employees', 'programmers'], 'combined_group', 'Combined Group'); // Get the modified data $modifiedData = $combiner->getData(); // Display the modified data echo "<pre>"; print_r($modifiedData); echo "</pre>";
You have javascript disabled. You will not be able to edit any code.