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

finlamit's avatar

Object arrays, grouping by value and separating into multiple arrays.

Hi

Can anyone help.

I have an array as such:

[
    {
        Name: "Lucy"
        Hair: "Blonde"
    },
    {
        Name: "Sam"
        Hair: "Brown"
    },
    {
        Name: "Paul"
        Hair: "Red"
    }
]

I need to separate this array into X number of arrays (x will depend on how many unique hair colours there are in the array ) so that I can display X number of tables/divs each displaying data for that hair colour. There may at any point be more hair colours added... So it needs to automatically create X number of arrays.

e.g.

<div>
    <h1>Students with Blonde Hair</h1>
    <ul>
        <li>
            Lucy
        </li>
    </ul>
</div>

<div>
    <h1>Students with Brown Hair</h1>
    <ul>
        <li>
            Sam
        </li>
    </ul>
</div>
...

Any ideas how I go about doing this? The data is being pulled from an api, which is just a long list of students.

Thanks

M

0 likes
2 replies
piljac1's avatar

You only need a single easy loop. Lodash is not needed.

Let's say the array you posted above is $students

// Array containing grouped results
$studentsByHairColor = [];

// Loop through each object in your array and assign the student name to a key representing his or her hair color
foreach ($students as $student)
    $studentsByHairColor[$student->Hair][] = $student->Name;

// Optional : Sort array's first level keys (hair colors) in alphabetical order
ksort($studentsByHairColor);

As simple as that !

Please or to participate in this conversation.