Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

php - How to group a multidimensional array by a particular subarray value?

I have a multidimensional array and am trying to group them according to the value in a specific column.

I'm trying to group them by level, but I won't actually know the level beforehand. So, it's not like I can put it in a for loop and say while $i < 7, because I won't know that 7 is the maximum value for the level key, and frankly, I'm not sure that's how I would need to do it even if I did...

Array (
   [0] => Array (
          [cust] => XT8900
          [type] => standard
          [level] => 1
          )
   [1] => Array (
          [cust] => XT8944
          [type] => standard
          [level] => 1
          )
   [2] => Array (
          [cust] => XT8922
          [type] => premier
          [level] => 3
          )
   [3] => Array (
          [cust] => XT8816
          [type] => permier
          [level] => 3
          )
   [4] => Array (
          [cust] => XT7434
          [type] => standard
          [level] => 7
          )
)

What I'm hoping to produce:

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
                 )
          )
)
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Best way, if you have control over building the initial array, is just set things up like that at the start as you add entries.

If not then build a temporary array to sort:

foreach ($input_arr as $key => &$entry) {
    $level_arr[$entry['level']][$key] = $entry;
}

Leaves you with the form you wanted and everything referenced together.

Build the array like that in the first place though if at all possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...