Group 2D array data using column values to generate 3D array
P粉022140576
2023-08-22 18:37:00
<p>I have a multidimensional array that I want to group based on the values in a specific column. </p>
<p>I want to group based on <code>level</code>, but I don’t know the value of level in advance. So, I can't say <code>while $i < 7</code> like in the <code>for</code> loop, because I don't know that <code>7</code> is the level key of the maximum value, and even if I knew I'm not sure I'd need to do that. </p>
<pre class="brush:php;toolbar:false;">[
['cust' => 'XT8900', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8944', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8922', 'type' => 'premier', 'level' => 3],
['cust' => 'XT8816', 'type' => 'permier', 'level' => 3],
['cust' => 'XT7434', 'type' => 'standard', 'level' => 7],
]</pre>
<p>Desired result: </p>
<pre class="brush:php;toolbar:false;">Array (
[1] => Array (
[0] => Array (
[cust] => XT8900
[type] => standard
)
[1] => Array (
[cust] => XT8944
[type] => standard
)
)
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
)</pre>
<p><br /></p>
The best approach is if you have control over building the initial array, then just set it up at the beginning when adding entries.
If there is no control, a temporary array is constructed for sorting:
This gives you the form you want, with all the references together.
If possible, initially build the array like this.
First, you need to group them by level
Use foreach to loop through the array, check if the level is the same as the previous item, then group it with that array
print($grouparr);The output will be displayed in the format you want
You can also try
will be displayed
or
will be displayed