简体   繁体   中英

php multiple array with same key

I know there is huge posts about this problem.. but I'm failed to fixed this with my little knowledge. Hope someone who expertise this filed maybe help!

Here is my array

Array
(
    [0] => Array
        (
            [category] => 9
            [course] => 80
            [subject] => 759
        )

    [1] => Array
        (
            [category] => 9
            [course] => 80
            [subject] => 760
        )

    [2] => Array
        (
            [category] => 11
            [course] => 97
            [subject] => 862
        )

    [3] => Array
        (
            [category] => 11
            [course] => 97
            [subject] => 865
        )

    [4] => Array
        (
            [category] => 11
            [course] => 97
            [subject] => 866
        )

    [5] => Array
        (
            [category] => 11
            [course] => 87
            [subject] => 758
        )
    [6] => Array
        (
            [category] => 9
            [course] => 25
            [subject] => 125
        )

)

Now I want to print same key value once only. So my expected result like this:

category 9

  • course 80 = subject 759, 760
  • course 25 = subject 125

category 11

  • course 97 = subject 862, 865, 866
  • course 87 = subject 758

I tried from yesterday night but can't print same key value once like this

You would need to rearrange the array:

<?php
    $newarray = [];
    foreach ($array as $entry) {
        $newarray[$entry['category']][$entry['course']] .= ' ' . $entry['subject'];
    }
?>

It may need some validation and changes, but you should end up with an array of organized data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM