3v4l.org

run code in 300+ PHP versions simultaneously
<?php // Data coming from MySQL Database $rowData = []; $rowData[] = ['id' => 74, 'name' => 'First Store', 'categories' => 'Food']; $rowData[] = ['id' => 74, 'name' => 'First Store', 'categories' => 'DVDs']; $rowData[] = ['id' => 1, 'name' => 'Second Store', 'categories' => 'Food']; $rowData[] = ['id' => 1, 'name' => 'Second Store', 'categories' => 'Toys']; $rowData[] = ['id' => 1, 'name' => 'Second Store', 'categories' => 'Toys']; $rowData[] = ['id' => 1, 'name' => 'Second Store', 'categories' => 'Clothing']; $rowData[] = ['id' => 3, 'name' => 'Third Store', 'categories' => 'Toys']; $rowData[] = ['id' => 3, 'name' => 'Third Store', 'categories' => 'Clothing']; $rowData[] = ['id' => 3, 'name' => 'Third Store', 'categories' => 'Clothing']; /** * Check if store category name already added to store record */ function categoryExistsAlready($categories, $category) { foreach($categories as $key => $catArr) { if(strtolower($catArr['name']) === strtolower($category)) { return true; } } return false; } $storeTracker = []; foreach($rowData as $key => $storeData) { $storeCategory = $storeData['categories']; $storeId = $storeData['id']; // If store exists, add category to categories array if (array_key_exists($storeId, $storeTracker)) { if (!categoryExistsAlready($storeTracker[$storeId]['categories'], $storeCategory)) { $storeTracker[$storeId]['categories'][] = ['name' => $storeCategory]; } continue; } // Update store categories to be array with category $storeData['categories'] = []; $storeData['categories'][] = ['name' => $storeCategory]; // Add store data to overall tracking array $storeTracker[$storeId] = $storeData; } // Format JSON response $jsonReturn = '['; $i = count($storeTracker); foreach($storeTracker as $storeId => $storeData) { $i--; $jsonReturn .= json_encode($storeData); // Determine last comma separating objects if ($i > 0) { $jsonReturn .= ','; } } $jsonReturn .= ']'; echo $jsonReturn;
Output for 7.1.25 - 7.1.28, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
[{"id":74,"name":"First Store","categories":[{"name":"Food"},{"name":"DVDs"}]},{"id":1,"name":"Second Store","categories":[{"name":"Food"},{"name":"Toys"},{"name":"Clothing"}]},{"id":3,"name":"Third Store","categories":[{"name":"Toys"},{"name":"Clothing"}]}]

preferences:
134.42 ms | 404 KiB | 166 Q