Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gabotronix's avatar

Create an object of arrays from each result of a query

Hi everybody, I have a query which takes the "name" parameter of all product categories in my backend, what I want to do is create an object of empty arrays where each empty array key is the name of the product category:

public function getProductCategoriesArray()
    {
        $productcategories = ProductCategory::pluck('name')->get();

        return response()->json([
            'productcategories' => $productcategories,
        ]);
    }

As yu can see I'm json encoding the result since I'll be doing some operations on the resulting object/array.

The result would be something like this:

$productCategories =  { Category1:[], Category2:[], Category2:[], Category3:[] }

or like this instead?

$productCategories =  [ Category1:[], Category2:[], Category2:[], Category3:[] ]

I'm a bit confused on this one. That is array of arrays or object of arrays, I think the first one is for js objects but may need some clarification on this.

0 likes
1 reply
lostdreamer_nl's avatar
Level 53

This will do what you're trying:

public function getProductCategoriesArray()
    {
        $productcategories = ProductCategory::get()->pluck('name', 'name')->map(function($cat) {
            return [];
        });

        return response()->json([
            'productcategories' => $productcategories,
        ]);
    }

The result will be an object with empty arrays.

{
  productcategories: {
    Category1: [],
    Category2: [],
    Category3: [],
  }
}

In Javascript, an array can only have 0 -> xxx as keys, it's not like PHP where we have Indexed & Associative arrays, Associative arrays will always become objects when converted to javascript.

Please or to participate in this conversation.