Skip to content

array_group_by helper function does not accept array of objects #10225

Description

@daveherman71

PHP Version

8.4

CodeIgniter4 Version

4.7.2

CodeIgniter4 Installation Method

Composer (using codeigniter4/appstarter)

Which operating systems have you tested for this bug?

Windows

Which server did you use?

cli-server (PHP built-in webserver)

Environment

production, development

Database

No response

What happened?

I have an array of objects. Each object contains a property called group. I would like to generate a multi-dimensional array where the keys are the group name and the values are an array of each object that matches that key. My code is as follows:

helper('array');
$groupedArray = array_group_by($originalArray, [ 'group' ]);

I get the following error:

[TypeError]
CodeIgniter\Helpers\Array\ArrayHelper::arrayAttachIndexedValue(): Argument #2 ($row) must be of type array, stdClass given, called in C:\inetpub\wwwroot\ims\vendor\codeigniter4\framework\system\Helpers\Array\ArrayHelper.php on line 197
at SYSTEMPATH\Helpers\Array\ArrayHelper.php:209

Steps to Reproduce

helper('array');

$json = '[{ "id": 1, "name": "Giraffe", "group": "Mammals" }, { "id": 2, "name": "Zebra", "group": "Mammals" }, { "id": 3, "name": "Crow", "group": "Birds" }]';

$groupedArray = array_group_by(json_decode($json), [ 'group' ]);

print_r($groupedArray);

Expected Output

I expected to get the following output

Array
(
    [Mammals] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [name] => Giraffe
                    [group] => Mammals
                )

            [1] => stdClass Object
                (
                    [id] => 2
                    [name] => Zebra
                    [group] => Mammals
                )

        )

    [Birds] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 3
                    [name] => Crow
                    [group] => Birds
                )
        )
)

Anything else?

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementPRs that improve existing functionalities

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions